package com.lanyou.esb.service;

import java.io.File;
import java.net.ConnectException;
import java.rmi.NoSuchObjectException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.wsdl.WSDLException;

import org.apache.commons.collections4.map.MultiKeyMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.commons.net.ftp.FTP;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import redis.clients.jedis.exceptions.JedisException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.datadictionary.UserLogOpt;
import com.lanyou.cook.entity.domain.FieldSystem;
import com.lanyou.cook.entity.domain.ParamSetting;
import com.lanyou.cook.entity.domain.userManagement.User;
import com.lanyou.cook.paramsetting.ParamSettingReppository;
import com.lanyou.cook.repository.FieldSystemRepository;
import com.lanyou.cook.repository.userManagement.UserRepository;
import com.lanyou.cook.service.SendEmailService;
import com.lanyou.cook.service.UserLogService;
import com.lanyou.cook.service.security.UserSessionService;
import com.lanyou.cook.util.gson.GsonUtil;
import com.lanyou.esb.common.CommonUtils;
import com.lanyou.esb.datadictionary.AuditStatusType;
import com.lanyou.esb.datadictionary.BundleModeType;
import com.lanyou.esb.datadictionary.BundleType;
import com.lanyou.esb.datadictionary.EnableType;
import com.lanyou.esb.datadictionary.FtpAccessType;
import com.lanyou.esb.datadictionary.FtpHostType;
import com.lanyou.esb.datadictionary.FtpPassiveMode;
import com.lanyou.esb.datadictionary.FtpSourceFileHanderType;
import com.lanyou.esb.datadictionary.FtpTargetFileHanderType;
import com.lanyou.esb.datadictionary.IfCostType;
import com.lanyou.esb.datadictionary.IfReqType;
import com.lanyou.esb.datadictionary.IfStatusType;
import com.lanyou.esb.datadictionary.IfType;
import com.lanyou.esb.datadictionary.InterfaceIsPublicType;
import com.lanyou.esb.datadictionary.IsolationStatus;
import com.lanyou.esb.datadictionary.ParameterType;
import com.lanyou.esb.datadictionary.ScheduleType;
import com.lanyou.esb.datadictionary.TimeUnit;
import com.lanyou.esb.datadictionary.TraceType;
import com.lanyou.esb.datadictionary.TransportProtocolType;
import com.lanyou.esb.entity.DefinedBundle;
import com.lanyou.esb.entity.Ftp;
import com.lanyou.esb.entity.FtpServer;
import com.lanyou.esb.entity.Http;
import com.lanyou.esb.entity.IfParameter;
import com.lanyou.esb.entity.IfReqQuantity;
import com.lanyou.esb.entity.IfSchedule;
import com.lanyou.esb.exception.BundleActionException;
import com.lanyou.esb.exception.ServerMixException;
import com.lanyou.esb.exception.ServiceHandlerException;
import com.lanyou.esb.redis.proxy.impl.HttpJedisProxy;
import com.lanyou.esb.redis.proxy.impl.IfReqQuantityJedisProxy;
import com.lanyou.esb.redis.vo.HttpVo;
import com.lanyou.esb.redis.vo.IfReqQuantityVo;
import com.lanyou.esb.repository.DefinedBundleRepository;
import com.lanyou.esb.repository.FtpRepository;
import com.lanyou.esb.repository.FtpServerRepository;
import com.lanyou.esb.repository.HttpRepository;
import com.lanyou.esb.repository.IfAlarmRepository;
import com.lanyou.esb.repository.IfParameterRepository;
import com.lanyou.esb.repository.IfReqQuantityRepository;
import com.lanyou.esb.repository.IfScheduleRepository;
import com.lanyou.esb.servicemix.bean.Bundle;
import com.lanyou.esb.servicemix.monitor.ESBServer;
import com.lanyou.esb.servicemix.monitor.ESBServerFactory;
import com.lanyou.esb.servicemix.monitor.rest.MonitorService;
import com.lanyou.esb.servicemix.monitor.rest.bean.Property;
import com.lanyou.esb.servicemix.util.BundleHandleUtil;
import com.lanyou.esb.servicemix.util.ConnetServerTest;
import com.lanyou.esb.servicemix.util.FtpRouteHandleUtil;
import com.lanyou.esb.util.FileDelCilent;
import com.lanyou.esb.web.ServiceManagerController;
import com.lanyou.esb.web.param.BaseServiceManagementParam;

/**
 * 服务管理服务类
 * 
 * @author ly-yangchenrui
 *
 */
@Service
public class ServiceManagerService {

	@PersistenceContext
	private EntityManager entityManager;

	@Autowired
	UserSessionService userSessionService;

	@Autowired
	private DefinedBundleRepository definedBundleRepository;

	@Autowired
	private HttpRepository httpRepository;

	@Autowired
	private FtpRepository ftpRepository;
	
	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private SendEmailService sendEmailService;

	@Autowired
	private BaseServiceManagementService baseServiceManagementService;

	@Autowired
	private FieldSystemRepository fieldSystemRepository;

	@Autowired
	private IfReqQuantityRepository interfaceRequestQuantityRepository;

	@Autowired
	private IfScheduleRepository ifScheduleRepository;

	@Autowired
	private FtpServerRepository ftpServerRepository;

	@Autowired
	private WsdlMetaDataService wsdlMetaDataService;

	@Autowired
	private HttpJedisProxy httpJedisProxy;

	@Autowired
	private IfReqQuantityJedisProxy ifReqQuantityJedisProxy;

	@Autowired
	private IfParameterRepository interfaceParameterRepository;

	@Autowired
	private ParamSettingReppository paramSettingReppository;

	@Autowired
	private ESBServerFactory eSBServerFactory;

	@Autowired
	private UserLogService userLogService;

	@Autowired
	private IfAlarmRepository alarmRepository;
	
	private static Map<String, Ftp>  backUpFtpMap = new HashMap<String, Ftp>();
	
	private static Map<String, Set>  backUpRelationMap = new HashMap<String, Set>();
	
	/*@Autowired
	private CamelService camelService;*/

	private static FastDateFormat fastDateFormat1 = FastDateFormat
			.getInstance(Constants.DATETIME_PATTERN_1);

	/**
	 * 
	 * @param interfaceDatas
	 *            表单数据
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 * @throws NoSuchObjectException
	 */
	@Transactional
	public boolean httpServiceRegister(String interfaceDatas)
			throws ServiceHandlerException, NoSuchObjectException {
		String handlerType = new String("注册");
		// 后台表单校验
		formCheck(interfaceDatas, handlerType);
		// 将表单数据装成json对象
		JsonObject jsonData = GsonUtil.getDefaultJsonParser()
				.parse(interfaceDatas).getAsJsonObject().get("interfaceDatas")
				.getAsJsonObject();

		String interfaceCode = jsonData.get("interfaceCode").getAsString();
		String interfaceVersion = jsonData.get("interfaceVersion")
				.getAsString();
		//判断注册的接口名称是否已存在
		String interfaceName = jsonData.get("interfaceName").getAsString();
		long count = httpRepository.countByNameAndIsEnable(interfaceName, EnableType.ENABLE.ValueCode);
		if(count > 0){
			throw new ServiceHandlerException(
					CommonUtils.MSG_CURRENT_IF_NAME_ALREADY_REGISTERED,
					CommonUtils.CODE_CURRENT_IF_NAME_ALREADY_REGISTERED);
		}
		
		// 判断注册的接口是否已经存在
		Http http = httpRepository.findByCodeAndIsEnable(interfaceCode, EnableType.ENABLE.ValueCode);
		if (http != null) {
			throw new ServiceHandlerException(
					CommonUtils.MSG_CURRENT_IF_ALREADY_REGISTERED,
					CommonUtils.CODE_CURRENT_IF_ALREADY_REGISTERED);
		} else {
			http = new Http();
			http.setCode(jsonData.get("interfaceCode").getAsString());
		}

		// 设置可见范围系统
		List<String> fieldSystemIds = new ArrayList<>();
		String isPublic = jsonData.get("isPublic").getAsString();
		http.setIfPublic(isPublic);
		if (StringUtils.equals(isPublic,
				InterfaceIsPublicType.PRIVATE.ValueCode)) {
			JsonElement systemIds = jsonData.get("fieldSystemIds");
			if (systemIds != null) {
				JsonArray object = jsonData.get("fieldSystemIds")
						.getAsJsonArray();
				for (int i = 0; i < object.size(); i++) {
					fieldSystemIds.add(object.get(i).getAsString());
				}
				List<FieldSystem> fieldSystems = fieldSystemRepository
						.findAll(fieldSystemIds);
				http.getVisibleFieldSystems().clear();
				http.getVisibleFieldSystems().addAll(fieldSystems);
			}
		}

		String interfaceType = jsonData.get("interfaceType").getAsString();
		http.setType(interfaceType);
		// 根据接口类型设置请求报文
		if (StringUtils.equals(interfaceType, IfType.WS.ValueCode)) {
			// webservice
			http.setContentType(jsonData.get("soapProtocol").getAsString());
			http.setRequestMess(jsonData.get("requestParameterMsg")
					.getAsString());
		} else {
			// rest
			http.setRequestMess(jsonData.get("requestParameterMsg")
					.getAsString());
		}

		String bundleMode = jsonData.get("bundleMode").getAsString();
		if (StringUtils.equals(bundleMode, BundleModeType.PROXY_MODE.ValueCode)) {
			// 代理模式
			http.setBundleType(bundleMode);
			DefinedBundle definedBundle = definedBundleRepository
					.findByBundleName(Constants.COOKPROXY_NAME);
			Set<DefinedBundle> definedBundleSet = new HashSet<DefinedBundle>();
			definedBundleSet.add(definedBundle);
			http.setDefinedbundles(definedBundleSet);
			String priUrl = jsonData.get("interfaceOriginAddress")
					.getAsString();
			http.setPriUrl(priUrl);

			// 设置请求webservice接口的soapAction标识
			if (StringUtils.equals(interfaceType, IfType.WS.ValueCode)) {
				String interfaceValue = jsonData.get("interfaceValue")
						.getAsString();
				String soapActionUri = "";
				try {
					soapActionUri = wsdlMetaDataService
							.getSoapActionByOperation(priUrl, interfaceValue);
				} catch (WSDLException e) {
					throw new ServiceHandlerException(
							CommonUtils.MSG_GET_SOAPACTIONURI_FAIED,
							CommonUtils.CODE_GET_SOAPACTIONURI_FAIED);
				} catch (Exception e) {
					throw new ServiceHandlerException(
							CommonUtils.MSG_GET_SOAPACTIONURI_FAIED,
							CommonUtils.CODE_GET_SOAPACTIONURI_FAIED);
				}
				http.setSoapActionUri(soapActionUri);
			}
		} else {
			// 自定义模式

			// 测试servicemix服务器是否可以连通
			try {
				ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
			} catch (ServerMixException e) {
				throw new ServiceHandlerException("注册失败," + e.getMessage(),
						CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
			}

			http.setBundleType(bundleMode);
			http.getDefinedbundles().clear();
			Set<DefinedBundle> bundles = http.getDefinedbundles();
			// 接口部署包设置
			JsonElement packJar = jsonData.get("packageJarNames");
			if (packJar != null) {
				JsonArray object = jsonData.get("packageJarNames")
						.getAsJsonArray();
				for (int i = 0; i < object.size(); i++) {
					DefinedBundle definedBundle = new DefinedBundle();
					definedBundle.setIsDefinedBundle("1");
					definedBundle.setBundleJarName(object.get(i).getAsString());
					definedBundle.setType(BundleType.SELFDEFINED.ValueCode);
					definedBundleRepository.save(Arrays.asList(definedBundle));
					bundles.add(definedBundle);
				}

				// 接口部署依赖包
				JsonElement dependentPackageIds = jsonData
						.get("dependsPackageIds");
				if (dependentPackageIds != null) {
					JsonArray dependentPackageObject = jsonData.get(
							"dependsPackageIds").getAsJsonArray();
					for (int i = 0; i < dependentPackageObject.size(); i++) {
						DefinedBundle definedBundle;
						DefinedBundle findBundle = definedBundleRepository
								.findByBundleCode(dependentPackageObject.get(i)
										.getAsString());
						if (findBundle == null) {
							definedBundle = new DefinedBundle();
							Bundle bundle = null;
							try {
								/*
								 * List<MonitorService> monitorServices =
								 * eSBServerFactory.getMonitorService(); for
								 * (MonitorService monitorService :
								 * monitorServices) { bundle =
								 * monitorService.getBundleById
								 * (dependentPackageObject
								 * .get(i).getAsInt()).getData().get(0);
								 * 
								 * }
								 */
								bundle = eSBServerFactory
										.getMonitorService()
										.get(0)
										.getBundleById(
												dependentPackageObject.get(i)
														.getAsInt()).getData()
										.get(0);

							} catch (Exception e) {
								if (e.getCause() instanceof ConnectException) {
									throw new ServiceHandlerException(
											"注册失败，" + CommonUtils.MSG_CONNECT_SERVICEMIX_FAIED,
											CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);

								} else {
									throw new ServiceHandlerException(
											"注册失败，" + CommonUtils.MSG_CALL_INTERFACES_FAIED,
											CommonUtils.CODE_CALL_INTERFACES_FAIED);
								}
							}
							for (Property property : bundle.getProps()) {
								if (StringUtils.equals(property.getKey(),
										"Bundle Location")) {
									String bundleLocation = property.getValue()
											.toString();
									definedBundle
											.setBundleLocation(bundleLocation);
									if (bundleLocation.contains(":")) {
										Pattern patternBundleLocation = Pattern
												.compile(":");
										Matcher matcherBundleLocation = patternBundleLocation
												.matcher(bundleLocation);
										String jarBundleLocation = "";
										if (matcherBundleLocation.find()) {
											jarBundleLocation = bundleLocation
													.substring(
															bundleLocation
																	.lastIndexOf(matcherBundleLocation
																			.group(0)) + 1,
															bundleLocation
																	.length());
											definedBundle
													.setBundleJarName(jarBundleLocation);
										}
									} else {
										definedBundle
												.setBundleJarName(bundleLocation);
									}
								}
							}
							definedBundle.setIsDefinedBundle("0");
							definedBundle.setBundleCode(String.valueOf(bundle
									.getId()));
							definedBundle.setType(BundleType.BASE.ValueCode);
							definedBundle.setBundleName(bundle.getName());
							definedBundle.setVersion(bundle.getVersion());
							definedBundle.setStatus(bundle.getState());
							definedBundleRepository.save(Arrays
									.asList(definedBundle));

						} else {
							definedBundle = findBundle;
						}
						bundles.add(definedBundle);
					}
				}

			} else {
				throw new ServiceHandlerException(
						"注册失败，" + CommonUtils.MSG_UPLOAD_JAR_FILE_FAIED,
						CommonUtils.CODE_UPLOAD_JAR_FILE_FAIED);
			}
		}
		http.setName(jsonData.get("interfaceName").getAsString());
		http.setVersion(jsonData.get("interfaceVersion").getAsString());
		http.setDataFormate(jsonData.get("interfaceDataFormat").getAsString());
		http.setOperationType(jsonData.get("operationType").getAsString());
		http.setTransportProtocol(jsonData.get("transportProtocol")
				.getAsString());
		http.setReturnMess(jsonData.get("responseParametersMsg").getAsString());
		http.setAuthType(jsonData.get("authencationMode").getAsString());
		http.setOvertime(jsonData.get("overTimeSetting").getAsString());
		http.setAuditStatus(AuditStatusType.UNAUDITED.ValueCode);
		http.setIfOlation(IsolationStatus.NOT_ISOLATION.ValueCode);
		http.setIfCost(IfCostType.FREE.ValueCode);
		http.setIsTrace(TraceType.NOTRACE.ValueCode);
		http.setStatus(IfStatusType.DISABLE.ValueCode);
		http.setIsEnable(EnableType.ENABLE.ValueCode);
		FieldSystem fieldSystem = fieldSystemRepository.findOne(FieldSystem
				.idSpecification(jsonData.get("systemId").getAsString()));
		http.setFieldSystem(fieldSystem);
		http.setSystemCode(fieldSystem.getCode());
		String transportProtocol = TransportProtocolType.get(jsonData.get(
				"transportProtocol").getAsString()).ValueName;

		ParamSetting paramSetting = paramSettingReppository
				.findByParamName(Constants.SERVERADDRESS);
		
		if (StringUtils.equals(interfaceType, IfType.WS.ValueCode)) {
			//webservice
			http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
			+ "/" + fieldSystem.getCode() + "/"
			+ jsonData.get("interfaceVersion").getAsString() + "/"
			+ jsonData.get("interfaceCode").getAsString() + "/");
		}else{
			//rest
			if(StringUtils.equals(jsonData.get("interfaceRequestMethod").getAsString(), IfReqType.GET.ValueCode)){
				//GET请求
				String resultStr = "";
				// 获取接口请求参数并保存
				StringBuilder queryString = new StringBuilder();
				JsonArray jsonReqArray = jsonData.get("requestParameters").getAsJsonArray();
				if(jsonReqArray.size() > 0){
					for (int i = 0; i < jsonReqArray.size(); i++) {
						JsonObject jsonParmData = jsonReqArray.get(i).getAsJsonObject();
						String paramName = jsonParmData.get("reqParameterName").getAsString();
						String paramDefaultValue = jsonParmData.get("reqParameterDefaultValue").getAsString();
						String resutlString = paramName + "=" + paramDefaultValue + "&";
						queryString.append(resutlString);
					}
						
					resultStr = queryString.toString().substring(0, queryString.length() - 1);
					//有参数
					http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
							+ "/" + fieldSystem.getCode() + "/"
							+ jsonData.get("interfaceVersion").getAsString() + "/"
							+ jsonData.get("interfaceCode").getAsString() + "/" + resultStr);
				}else{
					http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
					+ "/" + fieldSystem.getCode() + "/"
					+ jsonData.get("interfaceVersion").getAsString() + "/"
					+ jsonData.get("interfaceCode").getAsString() + "/");
				}
				
				http.setRequest(IfReqType.GET.ValueCode);
			}else{
				//POST请求
				http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
				+ "/" + fieldSystem.getCode() + "/"
				+ jsonData.get("interfaceVersion").getAsString() + "/"
				+ jsonData.get("interfaceCode").getAsString() + "/");
				
				http.setRequest(IfReqType.POST.ValueCode);
			}
		}

		/*
		 * http.setPubUrl(transportProtocol + "://" + Constants.SERVERADDRESS +
		 * "/" + fieldSystem.getCode() + "/" +
		 * jsonData.get("interfaceVersion").getAsString() +"/" +
		 * jsonData.get("interfaceCode").getAsString() + "/");
		 */
		http.setDesc(jsonData.get("interfaceDes").getAsString());

		httpRepository.save(Arrays.asList(http));

		// 获取请求流量阀值和最大值并保存
		IfReqQuantity interfaceRequestQuantity = new IfReqQuantity();
		interfaceRequestQuantity.setRequestThreshold(jsonData.get(
				"alarmThreshold").getAsString());
		interfaceRequestQuantity.setRequestMax(jsonData.get("alarmMax")
				.getAsString());
		interfaceRequestQuantity.setRequestUnit(TimeUnit.DAY.ValueCode);
		interfaceRequestQuantity.setHttp(http);
		interfaceRequestQuantity.setIsEnable(EnableType.ENABLE.ValueCode);

		interfaceRequestQuantityRepository.save(Arrays
				.asList(interfaceRequestQuantity));
		// 更新reids服务器中对应的数据
		updateIfReqQuantityRedisData(interfaceRequestQuantity);

		// 获取接口请求参数并保存
		JsonElement requestParameters = jsonData.get("requestParameters");
		if (requestParameters != null) {
			JsonArray jsonReqArray = jsonData.get("requestParameters")
					.getAsJsonArray();
			for (int i = 0; i < jsonReqArray.size(); i++) {
				JsonObject jsonParmData = jsonReqArray.get(i).getAsJsonObject();
				IfParameter interfaceParameter = new IfParameter();

				interfaceParameter.setName(jsonParmData.get("reqParameterName")
						.getAsString());
				interfaceParameter.setDataType(jsonParmData.get(
						"comboxReqParameterType").getAsString());
				interfaceParameter.setIsNeed(jsonParmData.get(
						"reqParameterIsMust").getAsString());
				interfaceParameter.setDefaultValue(jsonParmData.get(
						"reqParameterDefaultValue").getAsString());
				interfaceParameter.setDesc(jsonParmData.get("reqParameterDes")
						.getAsString());
				interfaceParameter.setHttp(http);
				interfaceParameter.setType(ParameterType.REQUEST.ValueCode);
				interfaceParameter.setIsEnable(EnableType.ENABLE.ValueCode);

				interfaceParameterRepository.save(Arrays
						.asList(interfaceParameter));
			}
		}

		// 获取接口返回参数并保存
		JsonElement responseParameters = jsonData.get("responseParameters");
		if (responseParameters != null) {
			JsonArray jsonRepArray = jsonData.get("responseParameters")
					.getAsJsonArray();
			for (int i = 0; i < jsonRepArray.size(); i++) {
				JsonObject jsonParmData = jsonRepArray.get(i).getAsJsonObject();
				IfParameter interfaceParameter = new IfParameter();

				interfaceParameter.setName(jsonParmData.get("repParameterName")
						.getAsString());
				interfaceParameter.setDataType(jsonParmData.get(
						"comboxRepParameterType").getAsString());
				interfaceParameter.setIsNeed("0");
				interfaceParameter.setDesc(jsonParmData.get("repParameterDes")
						.getAsString());
				interfaceParameter.setHttp(http);
				interfaceParameter.setType(ParameterType.RETURN.ValueCode);
				interfaceParameter.setIsEnable(EnableType.ENABLE.ValueCode);

				interfaceParameterRepository.save(Arrays
						.asList(interfaceParameter));
			}
		}
		// 更新Redis服务器中对应的数据
		updateHttpRedisData(http);

		// 记录用户操作日志
		userLogService.save(UserLogOpt.MaintenanceServiceRegister, null, String
				.format("注册了“%s”接口", jsonData.get("interfaceName")
						.getAsString()));
		return true;
	}

	/**
	 * 
	 * @param interfaceDatas
	 *            表单数据
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 * @throws NoSuchObjectException
	 */
	@Transactional
	public boolean httpServiceUpdate(String interfaceDatas)
			throws ServiceHandlerException, NoSuchObjectException {
		String handlerType = new String("更新");
		// 后台表单校验
		formCheck(interfaceDatas, handlerType);

		// 将表单数据装成json对象
		JsonObject jsonData = GsonUtil.getDefaultJsonParser()
				.parse(interfaceDatas).getAsJsonObject().get("interfaceDatas")
				.getAsJsonObject();
		Http http = httpRepository.findOne(Http.idSpecification(jsonData.get(
				"id").getAsString()));

		// 判断注册的接口名称是否已存在
		String interfaceName = jsonData.get("interfaceName").getAsString();
		if(!StringUtils.equals(http.getName(), interfaceName)){
			//接口名称已改变
			long count = httpRepository.countByNameAndIsEnable(interfaceName, EnableType.ENABLE.ValueCode);
			if (count > 0) {
				throw new ServiceHandlerException(CommonUtils.MSG_CURRENT_IF_NAME_ALREADY_EXISTS,
						CommonUtils.CODE_CURRENT_IF_NAME_ALREADY_EXISTS);
			}
		}
				
				
		List<String> fieldSystemIds = new ArrayList<>();
		String isPublic = jsonData.get("isPublic").getAsString();
		http.setIfPublic(isPublic);
		if (StringUtils.equals(isPublic,
				InterfaceIsPublicType.PRIVATE.ValueCode)) {
			// 私有
			JsonArray object = jsonData.get("fieldSystemIds").getAsJsonArray();
			for (int i = 0; i < object.size(); i++) {
				fieldSystemIds.add(object.get(i).getAsString());
			}
			List<FieldSystem> fieldSystems = fieldSystemRepository
					.findAll(fieldSystemIds);
			http.getVisibleFieldSystems().clear();
			http.getVisibleFieldSystems().addAll(fieldSystems);
		} else {
			// 公开
			http.getVisibleFieldSystems().clear();
		}

		if (StringUtils.equals(http.getType(), IfType.WS.ValueCode)) {
			// wbservice传输协议
			http.setContentType(jsonData.get("soapProtocol").getAsString());
		} else {
			// rest
		}

		if (StringUtils.equals(http.getBundleType(),
				BundleModeType.PROXY_MODE.ValueCode)) {
			// 代理模式
			http.setPriUrl(jsonData.get("interfaceOriginAddress").getAsString());
		} else {
			// 自定义模式

			// 测试服务器是否可以连通
			try {
				ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
			} catch (ServerMixException e) {
				throw new ServiceHandlerException("更新失败，" + e.getMessage(),
						CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
			}

			http.getDefinedbundles().clear();
			Set<DefinedBundle> bundles = http.getDefinedbundles();

			// 获取要更新的接口部署包名称
			JsonArray object = jsonData.get("packageJarNames").getAsJsonArray();
			// 获取要更新的接口部署包id
			JsonArray objectIds = jsonData.get("bundleJarIds").getAsJsonArray();
			String bundleId = jsonData.get("httpBundleId").getAsString();
			if (objectIds.size() < 1) {
				DefinedBundle mainBundle = definedBundleRepository
						.findOne(DefinedBundle.idSpecification(bundleId));
				bundles.add(mainBundle);
			} else {
				if (StringUtils.equals(http.getAuditStatus(),
						AuditStatusType.UNAUDITED.ValueCode)) {
					// 未审核
					for (int i = 0; i < object.size(); i++) {
						DefinedBundle definedBundle = new DefinedBundle();
						definedBundle.setIsDefinedBundle("1");
						definedBundle.setBundleJarName(object.get(i)
								.getAsString());
						definedBundle.setType(BundleType.SELFDEFINED.ValueCode);
						definedBundleRepository.save(Arrays
								.asList(definedBundle));
						bundles.add(definedBundle);
					}
				} else {
					// 已审核
					// 更新接口部署包
					httpBundleInfoUpdate(bundles, object, objectIds);
				}

			}

			// 设置接口部署包依赖
			JsonElement dependentPackageIds = jsonData.get("dependsPackageIds");
			if (dependentPackageIds != null) {
				JsonArray dependentPackageObject = jsonData.get(
						"dependsPackageIds").getAsJsonArray();
				for (int i = 0; i < dependentPackageObject.size(); i++) {
					DefinedBundle definedBundle;
					DefinedBundle findBundle = definedBundleRepository
							.findByBundleCode(dependentPackageObject.get(i)
									.getAsString());
					if (findBundle == null) {
						definedBundle = new DefinedBundle();
						Bundle bundle = null;
						try {
							/*
							 * bundle =
							 * monitorService.getBundleById(dependentPackageObject
							 * .get(i).getAsInt()).getData().get(0);
							 */
							bundle = eSBServerFactory
									.getMonitorService()
									.get(0)
									.getBundleById(
											dependentPackageObject.get(i)
													.getAsInt()).getData()
									.get(0);
						} catch (Exception e) {
							if (e.getCause() instanceof ConnectException) {
								throw new ServiceHandlerException(
										"更新失败，" + CommonUtils.MSG_CONNECT_SERVICEMIX_FAIED,
										CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
							} else {
								throw new ServiceHandlerException(
										"更新失败，" + CommonUtils.MSG_CALL_INTERFACES_FAIED,
										CommonUtils.CODE_CALL_INTERFACES_FAIED);
							}
						}
						for (Property property : bundle.getProps()) {
							if (StringUtils.equals(property.getKey(),
									"Bundle Location")) {
								String bundleLocation = property.getValue()
										.toString();
								definedBundle.setBundleLocation(bundleLocation);
								if (bundleLocation.contains(":")) {
									Pattern patternBundleLocation = Pattern
											.compile(":");
									Matcher matcherBundleLocation = patternBundleLocation
											.matcher(bundleLocation);
									String jarBundleLocation = "";
									if (matcherBundleLocation.find()) {
										jarBundleLocation = bundleLocation
												.substring(
														bundleLocation
																.lastIndexOf(matcherBundleLocation
																		.group(0)) + 1,
														bundleLocation.length());
										definedBundle
												.setBundleJarName(jarBundleLocation);
									}
								} else {
									definedBundle
											.setBundleJarName(bundleLocation);
								}
							}
						}
						definedBundle.setIsDefinedBundle("0");
						definedBundle.setBundleCode(String.valueOf(bundle
								.getId()));
						definedBundle.setBundleName(bundle.getName());
						definedBundle.setVersion(bundle.getVersion());
						definedBundle.setType(BundleType.BASE.ValueCode);
						definedBundle.setStatus(bundle.getState());
						definedBundleRepository.save(Arrays
								.asList(definedBundle));

					} else {
						definedBundle = findBundle;
					}

					bundles.add(definedBundle);
				}
			}
		}

		http.setName(jsonData.get("interfaceName").getAsString());
		http.setCode(jsonData.get("interfaceCode").getAsString());
		http.setVersion(jsonData.get("interfaceVersion").getAsString());
		http.setDataFormate(jsonData.get("interfaceDataFormat").getAsString());
		http.setOperationType(jsonData.get("operationType").getAsString());
		http.setTransportProtocol(jsonData.get("transportProtocol")
				.getAsString());
		// http.setBundleType(jsonData.get("bundleMode").getAsString());
		// http.setPriUrl(jsonData.get("interfaceOriginAddress").getAsString());
		http.setDesc(jsonData.get("interfaceDes").getAsString());

		http.setRequestMess(jsonData.get("requestParameterMsg").getAsString());
		http.setReturnMess(jsonData.get("responseParametersMsg").getAsString());
		http.setIfOlation(IsolationStatus.NOT_ISOLATION.ValueCode);
		http.setAuthType(jsonData.get("authencationMode").getAsString());
		http.setOvertime(jsonData.get("overTimeSetting").getAsString());
		http.setIsTrace(TraceType.NOTRACE.ValueCode);
		// http.setAuditStatus(AuditStatusType.UNAUTHORIZED.ValueCode);
		// http.setIfCost(IfCostType.FREE.ValueCode);
		// http.setType(jsonData.get("interfaceType").getAsString());

		FieldSystem fieldSystem = fieldSystemRepository.findOne(FieldSystem
				.idSpecification(jsonData.get("systemId").getAsString()));
		http.setFieldSystem(fieldSystem);
		http.setSystemCode(fieldSystem.getCode());
		String transportProtocol = TransportProtocolType.get(jsonData.get(
				"transportProtocol").getAsString()).ValueName;

		ParamSetting paramSetting = paramSettingReppository
				.findByParamName(Constants.SERVERADDRESS);
		
		if (StringUtils.equals(http.getType(), IfType.WS.ValueCode)) {
			//webservice
			http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
			+ "/" + fieldSystem.getCode() + "/"
			+ jsonData.get("interfaceVersion").getAsString() + "/"
			+ jsonData.get("interfaceCode").getAsString() + "/");
		}else{
			//rest
			if(StringUtils.equals(jsonData.get("interfaceRequestMethod").getAsString(), IfReqType.GET.ValueCode)){
				//GET请求
				String resultStr = "";
				// 获取接口请求参数并保存
				StringBuilder queryString = new StringBuilder();
				JsonArray jsonReqArray = jsonData.get("requestParameters").getAsJsonArray();
				if(jsonReqArray.size() > 0){
					for (int i = 0; i < jsonReqArray.size(); i++) {
						JsonObject jsonParmData = jsonReqArray.get(i).getAsJsonObject();
						String paramName = jsonParmData.get("reqParameterName").getAsString();
						String paramDefaultValue = jsonParmData.get("reqParameterDefaultValue").getAsString();
						String resutlString = paramName + "=" + paramDefaultValue + "&";
						queryString.append(resutlString);
					}
						
					resultStr = queryString.toString().substring(0, queryString.length() - 1);
					//有参数
					http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
							+ "/" + fieldSystem.getCode() + "/"
							+ jsonData.get("interfaceVersion").getAsString() + "/"
							+ jsonData.get("interfaceCode").getAsString() + "/" + resultStr);
				}else{
					http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
					+ "/" + fieldSystem.getCode() + "/"
					+ jsonData.get("interfaceVersion").getAsString() + "/"
					+ jsonData.get("interfaceCode").getAsString() + "/");
				}
				
				http.setRequest(IfReqType.GET.ValueCode);
			}else{
				//POST请求
				http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
				+ "/" + fieldSystem.getCode() + "/"
				+ jsonData.get("interfaceVersion").getAsString() + "/"
				+ jsonData.get("interfaceCode").getAsString() + "/");
				
				http.setRequest(IfReqType.POST.ValueCode);
			}
		}

		/*
		 * http.setPubUrl(transportProtocol + "://" + Constants.SERVERADDRESS +
		 * "/" + fieldSystem.getCode() + "/" +
		 * jsonData.get("interfaceVersion").getAsString() +"/" +
		 * jsonData.get("interfaceCode").getAsString() + "/");
		 */
		// http.setIsEnable(IfEnableType.ENABLE.ValueCode);

		httpRepository.save(Arrays.asList(http));

		// 设置接口请求量数据
		IfReqQuantity interfaceRequestQuantity = interfaceRequestQuantityRepository
				.findOne(IfReqQuantity.idSpecification(jsonData.get("alarmId")
						.getAsString()));
		interfaceRequestQuantity.setRequestThreshold(jsonData.get(
				"alarmThreshold").getAsString());
		interfaceRequestQuantity.setRequestMax(jsonData.get("alarmMax")
				.getAsString());
		interfaceRequestQuantity.setRequestUnit(TimeUnit.DAY.ValueCode);
		interfaceRequestQuantity.setHttp(http);
		interfaceRequestQuantity.setIsEnable(EnableType.ENABLE.ValueCode);

		interfaceRequestQuantityRepository.save(Arrays
				.asList(interfaceRequestQuantity));
		// 更新Redis中对应的数据
		updateIfReqQuantityRedisData(interfaceRequestQuantity);

		// 获取要删除的参数进行删除操作
		JsonElement delParamIds = jsonData.get("deleteParamIds");
		if (delParamIds != null) {
			JsonArray objectParams = jsonData.get("deleteParamIds")
					.getAsJsonArray();
			for (int i = 0; i < objectParams.size(); i++) {
				if(StringUtils.isNotBlank(objectParams.get(i).getAsString())){
					interfaceParameterRepository.delete(objectParams.get(i)
							.getAsString());
				}
			}
		}

		// 获取请求参数并保存
		JsonElement requestParameters = jsonData.get("requestParameters");
		if (requestParameters != null) {
			JsonArray jsonReqArray = jsonData.get("requestParameters")
					.getAsJsonArray();

			for (int i = 0; i < jsonReqArray.size(); i++) {
				JsonObject jsonParmData = jsonReqArray.get(i).getAsJsonObject();
				IfParameter interfaceParameter = interfaceParameterRepository
						.findOne(IfParameter.idSpecification(jsonParmData.get(
								"reqParamId").getAsString()));
				if (interfaceParameter == null) {
					interfaceParameter = new IfParameter();
				}
				interfaceParameter.setName(jsonParmData.get("reqParameterName")
						.getAsString());
				interfaceParameter.setDataType(jsonParmData.get(
						"comboxReqParameterType").getAsString());
				interfaceParameter.setDefaultValue(jsonParmData.get(
						"reqParameterDefaultValue").getAsString());
				interfaceParameter.setIsNeed(jsonParmData.get(
						"reqParameterIsMust").getAsString());
				interfaceParameter.setDesc(jsonParmData.get("reqParameterDes")
						.getAsString());
				interfaceParameter.setHttp(http);
				interfaceParameter.setType(ParameterType.REQUEST.ValueCode);
				interfaceParameter.setIsEnable(EnableType.ENABLE.ValueCode);

				interfaceParameterRepository.save(Arrays
						.asList(interfaceParameter));

			}
		}

		// 获取返回参数并保存
		JsonElement responseParameters = jsonData.get("responseParameters");
		if (responseParameters != null) {
			JsonArray jsonRepArray = jsonData.get("responseParameters")
					.getAsJsonArray();

			for (int i = 0; i < jsonRepArray.size(); i++) {
				JsonObject jsonParmData = jsonRepArray.get(i).getAsJsonObject();
				IfParameter interfaceParameter = interfaceParameterRepository
						.findOne(IfParameter.idSpecification(jsonParmData.get(
								"repParamId").getAsString()));
				if (interfaceParameter == null) {
					interfaceParameter = new IfParameter();
				}

				interfaceParameter.setName(jsonParmData.get("repParameterName")
						.getAsString());
				interfaceParameter.setDataType(jsonParmData.get(
						"comboxRepParameterType").getAsString());
				interfaceParameter.setIsNeed("0");
				interfaceParameter.setDesc(jsonParmData.get("repParameterDes")
						.getAsString());
				interfaceParameter.setHttp(http);
				interfaceParameter.setType(ParameterType.RETURN.ValueCode);
				interfaceParameter.setIsEnable(EnableType.ENABLE.ValueCode);

				interfaceParameterRepository.save(Arrays
						.asList(interfaceParameter));

			}
		}
		// 更新Redis中对应的数据
		updateHttpRedisData(http);
		// 记录用户操作日志
		userLogService.save(UserLogOpt.MaintenanceBusinessServiceManagement,
				null, String.format("更新了“%s”接口", jsonData.get("interfaceName")
						.getAsString()));
		return true;
	}

	/**
	 * webservice和rest接口的版本升级
	 * 
	 * @param interfaceDatas
	 *            表单数据
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 * @throws NoSuchObjectException
	 */
	@Transactional
	public boolean httpServiceUpVersion(String interfaceDatas)
			throws ServiceHandlerException, NoSuchObjectException {
		// 将表单数据转成json对象
		JsonObject jsonData = GsonUtil.getDefaultJsonParser()
				.parse(interfaceDatas).getAsJsonObject().get("interfaceDatas")
				.getAsJsonObject();
		Http httpOrgin = httpRepository.findOne(Http.idSpecification(jsonData
				.get("id").getAsString()));
		
		// 判断版本升级的接口名称是否已存在
		String interfaceName = jsonData.get("interfaceName").getAsString();
		if (!StringUtils.equals(httpOrgin.getName(), interfaceName)) {
			// 接口名称已改变
			long count = httpRepository.countByNameAndIsEnable(interfaceName, EnableType.ENABLE.ValueCode);
			if (count > 0) {
				throw new ServiceHandlerException(CommonUtils.MSG_CURRENT_UP_IF_NAME_ALREADY_EXISTS,
						CommonUtils.CODE_CURRENT_UP_IF_NAME_ALREADY_EXISTS);
			}
		}
				
		Http http = new Http();

		// 设置接口的可见范围
		List<String> fieldSystemIds = new ArrayList<>();
		String isPublic = jsonData.get("isPublic").getAsString();
		http.setIfPublic(isPublic);
		if (StringUtils.equals(isPublic,
				InterfaceIsPublicType.PRIVATE.ValueCode)) {
			JsonArray object = jsonData.get("fieldSystemIds").getAsJsonArray();
			for (int i = 0; i < object.size(); i++) {
				fieldSystemIds.add(object.get(i).getAsString());
			}
			List<FieldSystem> fieldSystems = fieldSystemRepository
					.findAll(fieldSystemIds);
			http.getVisibleFieldSystems().clear();
			http.getVisibleFieldSystems().addAll(fieldSystems);
		} else {
			http.getVisibleFieldSystems().clear();
		}

		String interfaceType = jsonData.get("interfaceType").getAsString();
		http.setType(interfaceType);
		if (StringUtils.equals(interfaceType, IfType.WS.ValueCode)) {
			// webservice
			http.setContentType(jsonData.get("soapProtocol").getAsString());
			http.setRequestMess(jsonData.get("requestParameterMsg")
					.getAsString());
		} else {
			// rest
			http.setRequestMess(jsonData.get("requestParameterMsg")
					.getAsString());
		}

		if (StringUtils.equals(httpOrgin.getBundleType(),
				BundleModeType.PROXY_MODE.ValueCode)) {
			// 代理模式
			DefinedBundle definedBundle = definedBundleRepository
					.findByBundleName(Constants.COOKPROXY_NAME);
			Set<DefinedBundle> definedBundleSet = new HashSet<DefinedBundle>();
			definedBundleSet.add(definedBundle);
			http.setDefinedbundles(definedBundleSet);
			http.setPriUrl(jsonData.get("interfaceOriginAddress").getAsString());
		} else {
			// 自定义模式
			// 测试服务器是否可以连通
			try {
				ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
			} catch (ServerMixException e) {
				throw new ServiceHandlerException("版本升级失败，" + e.getMessage(),
						CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
			}

			http.getDefinedbundles().clear();
			Set<DefinedBundle> bundles = http.getDefinedbundles();
			// 设置接口部署包
			JsonElement packJar = jsonData.get("packageJarNames");
			if (packJar != null) {
				JsonArray object = jsonData.get("packageJarNames")
						.getAsJsonArray();

				if (StringUtils.equals(httpOrgin.getAuditStatus(),
						AuditStatusType.AUDITED.ValueCode)) {
					// 已审核
					httpBundleInfoVersionUpgrade(object, bundles);
				} else {
					// 未审核
					for (int i = 0; i < object.size(); i++) {
						DefinedBundle definedBundle = new DefinedBundle();
						definedBundle.setIsDefinedBundle("1");
						definedBundle.setBundleJarName(object.get(i)
								.getAsString());
						definedBundle.setType(BundleType.SELFDEFINED.ValueCode);
						definedBundleRepository.save(Arrays
								.asList(definedBundle));
						bundles.add(definedBundle);
					}
				}

				// 设置接口部署依赖包
				JsonElement dependentPackageIds = jsonData
						.get("dependsPackageIds");
				if (dependentPackageIds != null) {
					JsonArray dependentPackageObject = jsonData.get(
							"dependsPackageIds").getAsJsonArray();
					for (int i = 0; i < dependentPackageObject.size(); i++) {
						DefinedBundle definedBundle;
						DefinedBundle findBundle = definedBundleRepository
								.findByBundleCode(dependentPackageObject.get(i)
										.getAsString());
						if (findBundle == null) {
							definedBundle = new DefinedBundle();
							Bundle bundle = null;
							try {
								/*
								 * bundle = monitorService.getBundleById(
								 * dependentPackageObject
								 * .get(i).getAsInt()).getData().get(0);
								 */
								bundle = eSBServerFactory
										.getMonitorService()
										.get(0)
										.getBundleById(
												dependentPackageObject.get(i)
														.getAsInt()).getData()
										.get(0);
							} catch (Exception e) {
								if (e.getCause() instanceof ConnectException) {
									throw new ServiceHandlerException(
											"版本升级失败，" + CommonUtils.MSG_CONNECT_SERVICEMIX_FAIED,
											CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
								} else {
									throw new ServiceHandlerException(
											"版本升级失败，" + CommonUtils.MSG_CALL_INTERFACES_FAIED,
											CommonUtils.CODE_CALL_INTERFACES_FAIED);
								}
							}
							for (Property property : bundle.getProps()) {
								if (StringUtils.equals(property.getKey(),
										"Bundle Location")) {
									String bundleLocation = property.getValue()
											.toString();
									definedBundle
											.setBundleLocation(bundleLocation);
									if (bundleLocation.contains(":")) {
										Pattern patternBundleLocation = Pattern
												.compile(":");
										Matcher matcherBundleLocation = patternBundleLocation
												.matcher(bundleLocation);
										String jarBundleLocation = "";
										if (matcherBundleLocation.find()) {
											jarBundleLocation = bundleLocation
													.substring(
															bundleLocation
																	.lastIndexOf(matcherBundleLocation
																			.group(0)) + 1,
															bundleLocation
																	.length());
											definedBundle
													.setBundleJarName(jarBundleLocation);
										}
									} else {
										definedBundle
												.setBundleJarName(bundleLocation);
									}
								}
							}
							definedBundle.setIsDefinedBundle("0");
							definedBundle.setBundleCode(String.valueOf(bundle
									.getId()));
							definedBundle.setType(BundleType.BASE.ValueCode);
							definedBundle.setBundleName(bundle.getName());
							definedBundle.setVersion(bundle.getVersion());
							definedBundle.setStatus(bundle.getState());
							definedBundleRepository.save(Arrays
									.asList(definedBundle));

						} else {
							definedBundle = findBundle;
						}
						bundles.add(definedBundle);

					}
				}

			} else {
				throw new ServiceHandlerException(
						"版本升级失败，" + CommonUtils.MSG_UPLOAD_JAR_FILE_FAIED,
						CommonUtils.CODE_UPLOAD_JAR_FILE_FAIED);
			}
		}

		http.setName(jsonData.get("interfaceName").getAsString());
		http.setCode(jsonData.get("interfaceCode").getAsString());
		http.setVersion(jsonData.get("interfaceVersion").getAsString());
		http.setDataFormate(jsonData.get("interfaceDataFormat").getAsString());
		http.setOperationType(jsonData.get("operationType").getAsString());
		http.setTransportProtocol(jsonData.get("transportProtocol")
				.getAsString());
		http.setBundleType(httpOrgin.getBundleType());
		http.setDesc(jsonData.get("interfaceDes").getAsString());

		http.setAuditStatus(httpOrgin.getAuditStatus());
		http.setStatus(httpOrgin.getStatus());
		http.setReturnMess(jsonData.get("responseParametersMsg").getAsString());
		http.setAuthType(jsonData.get("authencationMode").getAsString());
		http.setOvertime(jsonData.get("overTimeSetting").getAsString());
		http.setIfOlation(IsolationStatus.NOT_ISOLATION.ValueCode);
		http.setIfCost(IfCostType.FREE.ValueCode);
		http.setIsTrace(TraceType.NOTRACE.ValueCode);
		http.setIsEnable(EnableType.ENABLE.ValueCode);

		FieldSystem fieldSystem = fieldSystemRepository.findOne(FieldSystem
				.idSpecification(jsonData.get("systemId").getAsString()));
		http.setFieldSystem(fieldSystem);
		http.setSystemCode(fieldSystem.getCode());

		String transportProtocol = TransportProtocolType.get(jsonData.get(
				"transportProtocol").getAsString()).ValueName;

		ParamSetting paramSetting = paramSettingReppository
				.findByParamName(Constants.SERVERADDRESS);
		
		if (StringUtils.equals(http.getType(), IfType.WS.ValueCode)) {
			//webservice
			http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
			+ "/" + fieldSystem.getCode() + "/"
			+ jsonData.get("interfaceVersion").getAsString() + "/"
			+ jsonData.get("interfaceCode").getAsString() + "/");
		}else{
			//rest
			if(StringUtils.equals(jsonData.get("interfaceRequestMethod").getAsString(), IfReqType.GET.ValueCode)){
				//GET请求
				String resultStr = "";
				// 获取接口请求参数并保存
				StringBuilder queryString = new StringBuilder();
				JsonArray jsonReqArray = jsonData.get("requestParameters").getAsJsonArray();
				if(jsonReqArray.size() > 0){
					for (int i = 0; i < jsonReqArray.size(); i++) {
						JsonObject jsonParmData = jsonReqArray.get(i).getAsJsonObject();
						String paramName = jsonParmData.get("reqParameterName").getAsString();
						String paramDefaultValue = jsonParmData.get("reqParameterDefaultValue").getAsString();
						String resutlString = paramName + "=" + paramDefaultValue + "&";
						queryString.append(resutlString);
					}
						
					resultStr = queryString.toString().substring(0, queryString.length() - 1);
					//有参数
					http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
							+ "/" + fieldSystem.getCode() + "/"
							+ jsonData.get("interfaceVersion").getAsString() + "/"
							+ jsonData.get("interfaceCode").getAsString() + "/" + resultStr);
				}else{
					http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
					+ "/" + fieldSystem.getCode() + "/"
					+ jsonData.get("interfaceVersion").getAsString() + "/"
					+ jsonData.get("interfaceCode").getAsString() + "/");
				}
				
				http.setRequest(IfReqType.GET.ValueCode);
			}else{
				//POST请求
				http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
				+ "/" + fieldSystem.getCode() + "/"
				+ jsonData.get("interfaceVersion").getAsString() + "/"
				+ jsonData.get("interfaceCode").getAsString() + "/");
				
				http.setRequest(IfReqType.POST.ValueCode);
			}
		}
		/*http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
				+ "/" + fieldSystem.getCode() + "/"
				+ jsonData.get("interfaceVersion").getAsString() + "/"
				+ jsonData.get("interfaceCode").getAsString() + "/");*/

		httpRepository.save(Arrays.asList(http));

		// 设置接口请求量
		IfReqQuantity interfaceRequestQuantity = new IfReqQuantity();
		interfaceRequestQuantity.setRequestThreshold(jsonData.get(
				"alarmThreshold").getAsString());
		interfaceRequestQuantity.setRequestMax(jsonData.get("alarmMax")
				.getAsString());
		interfaceRequestQuantity.setRequestUnit(TimeUnit.DAY.ValueCode);
		interfaceRequestQuantity.setHttp(http);
		interfaceRequestQuantity.setIsEnable(EnableType.ENABLE.ValueCode);

		interfaceRequestQuantityRepository.save(Arrays
				.asList(interfaceRequestQuantity));
		// 更新redis中的接口请求量
		updateIfReqQuantityRedisData(interfaceRequestQuantity);

		// 获取请求参数并保存
		JsonArray jsonReqArray = jsonData.get("requestParameters")
				.getAsJsonArray();

		for (int i = 0; i < jsonReqArray.size(); i++) {
			JsonObject jsonParmData = jsonReqArray.get(i).getAsJsonObject();
			IfParameter interfaceParameter = new IfParameter();

			interfaceParameter.setName(jsonParmData.get("reqParameterName")
					.getAsString());
			interfaceParameter.setDataType(jsonParmData.get(
					"comboxReqParameterType").getAsString());
			interfaceParameter.setDefaultValue(jsonParmData.get(
					"reqParameterDefaultValue").getAsString());
			interfaceParameter.setIsNeed(jsonParmData.get("reqParameterIsMust")
					.getAsString());
			interfaceParameter.setDesc(jsonParmData.get("reqParameterDes")
					.getAsString());
			interfaceParameter.setHttp(http);
			interfaceParameter.setType(ParameterType.REQUEST.ValueCode);
			interfaceParameter.setIsEnable(EnableType.ENABLE.ValueCode);

			interfaceParameterRepository
					.save(Arrays.asList(interfaceParameter));

		}

		// 获取返回参数并保存
		JsonArray jsonRepArray = jsonData.get("responseParameters")
				.getAsJsonArray();

		for (int i = 0; i < jsonRepArray.size(); i++) {
			JsonObject jsonParmData = jsonRepArray.get(i).getAsJsonObject();
			IfParameter interfaceParameter = new IfParameter();

			interfaceParameter.setName(jsonParmData.get("repParameterName")
					.getAsString());
			interfaceParameter.setDataType(jsonParmData.get(
					"comboxRepParameterType").getAsString());
			interfaceParameter.setIsNeed("0");
			interfaceParameter.setDesc(jsonParmData.get("repParameterDes")
					.getAsString());

			interfaceParameter.setHttp(http);
			interfaceParameter.setType(ParameterType.RETURN.ValueCode);
			interfaceParameter.setIsEnable(EnableType.ENABLE.ValueCode);

			interfaceParameterRepository
					.save(Arrays.asList(interfaceParameter));

		}
		// 更新Redis中对应的数据
		updateHttpRedisData(http);
		// 记录用户操作日志
		userLogService.save(UserLogOpt.MaintenanceBusinessServiceManagement,
				null, String.format("升级了“%s”接口的版本",
						jsonData.get("interfaceName").getAsString()));
		return true;
	}

	/**
	 * ftp接口注册
	 * 
	 * @param interfaceDatas
	 *            表单数据
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 */
	@Transactional
	public boolean ftpServiceRegister(String interfaceDatas)
			throws ServiceHandlerException {
		// 将表单数据转成json对象
		JsonObject jsonData = GsonUtil.getDefaultJsonParser()
				.parse(interfaceDatas).getAsJsonObject().get("interfaceDatas")
				.getAsJsonObject();
		String interfaceCode = jsonData.get("interfaceCode").getAsString();

		// 判断接口是否已存在
		String interfaceVersion = jsonData.get("interfaceVersion")
				.getAsString();
		Ftp ftp = ftpRepository.findByInterfacecodeAndIsEnable(interfaceCode, EnableType.ENABLE.ValueCode);
		if (ftp != null) {
			throw new ServiceHandlerException(
					CommonUtils.MSG_CURRENT_IF_ALREADY_REGISTERED,
					CommonUtils.CODE_CURRENT_IF_ALREADY_REGISTERED);
		} else {
			ftp = new Ftp();
			ftp.setInterfacecode(jsonData.get("interfaceCode").getAsString());
		}

		// 设置接口可见范围
		List<String> fieldSystemIds = new ArrayList<>();
		String isPublic = jsonData.get("isPublic").getAsString();
		ftp.setIfPublic(isPublic);
		if (StringUtils.equals(isPublic,
				InterfaceIsPublicType.PRIVATE.ValueCode)) {
			JsonArray object = jsonData.get("fieldSystemIds").getAsJsonArray();
			for (int i = 0; i < object.size(); i++) {
				fieldSystemIds.add(object.get(i).getAsString());
			}
			List<FieldSystem> fieldSystems = fieldSystemRepository
					.findAll(fieldSystemIds);
			ftp.getVisibleFieldSystems().clear();
			ftp.getVisibleFieldSystems().addAll(fieldSystems);
		}

		//设置ftp依赖的camel_ftp_bundle
		DefinedBundle definedBundle = definedBundleRepository
				.findByBundleName(Constants.COOKFTP_NAME);
		Set<DefinedBundle> definedBundleSet = new HashSet<DefinedBundle>();
		definedBundleSet.add(definedBundle);
		ftp.setDefinedbundles(definedBundleSet);
		
		
		ftp.setType(IfType.FTP.ValueCode);
		ftp.setInterfaceName(jsonData.get("interfaceName").getAsString());
		ftp.setVersion(jsonData.get("interfaceVersion").getAsString());
		ftp.setDesc(jsonData.get("interfaceDes").getAsString());
		ftp.setOvertime(jsonData.get("overTimeSetting").getAsString());
		ftp.setAuditStatus(AuditStatusType.UNAUDITED.ValueCode);
		ftp.setIfCost(IfCostType.FREE.ValueCode);
		ftp.setStatus(IfStatusType.DISABLE.ValueCode);
		ftp.setIsEnable(EnableType.ENABLE.ValueCode);

		FieldSystem fieldSystem = fieldSystemRepository.findOne(FieldSystem
				.idSpecification(jsonData.get("systemId").getAsString()));
		ftp.setFieldSystem(fieldSystem);
		ftp.setSystemCode(fieldSystem.getCode());
		
		boolean isSchedule = jsonData.get("isSchedule").getAsBoolean();
		if(isSchedule){
			ftp.setIsSchedule(ScheduleType.SCHEDULE.ValueCode);
		}else{
			ftp.setIsSchedule(ScheduleType.UNSCHEDULE.ValueCode);
		}
		
		ftp.setFileCachePath("./temp/" + ftp.getInterfaceName());
		ftpRepository.save(Arrays.asList(ftp));

		// 保存调度信息
		if(isSchedule){
			IfSchedule ifSchedule = new IfSchedule();
			ifSchedule.setName(jsonData.get("interfaceName").getAsString());
			ifSchedule.setIfType(IfType.FTP.ValueCode);
			try {
				ifSchedule.setBeginTime(fastDateFormat1.parse(jsonData.get(
						"beginTime").getAsString()));
				ifSchedule.setEndTime(fastDateFormat1.parse(jsonData.get("endTime")
						.getAsString()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
	
			ifSchedule.setRunWay(jsonData.get("runWay").getAsString());
			ifSchedule.setRunCyc(Integer.parseInt(jsonData.get("runCyc")
					.getAsString()));
			ifSchedule.setDayOfWeek(jsonData.get("dayOfWeek").getAsString());
			/*ifSchedule
					.setFileCachePath(jsonData.get("fileCachePath").getAsString());*/
			ifSchedule.setFtp(ftp);
			ifScheduleRepository.save(Arrays.asList(ifSchedule));
		}else{
			
		}

		// 设置源主机信息
		JsonArray jsonArraySource = jsonData.get("sourceDatas")
				.getAsJsonArray();

		for (int i = 0; i < jsonArraySource.size(); i++) {
			JsonObject jsonParmData = jsonArraySource.get(i).getAsJsonObject();
			FtpServer ftpServer = new FtpServer();

			FieldSystem system = fieldSystemRepository.findOne(FieldSystem
					.idSpecification(jsonParmData.get("fieldSystemId")
							.getAsString()));
			ftpServer.setOwnFieldSystem(system);
			ftpServer.setHost(jsonParmData.get("sourceHost").getAsString());
			ftpServer.setPort(jsonParmData.get("sourceHostPort").getAsString());
			boolean isAnonymous = jsonParmData.get("sourceIsAnmous")
					.getAsBoolean();
			if (isAnonymous) {
				// 匿名
				ftpServer.setIfAnonymous(FtpAccessType.ANONYMOUS.ValueCode);
				ftpServer.setUserName(Constants.FTP_ANONYMOUS_NAME);
			} else {
				// 非匿名
				ftpServer.setIfAnonymous(FtpAccessType.UNANONYMOUS.ValueCode);
				ftpServer.setUserName(jsonParmData.get("sourceUserName")
						.getAsString());
				ftpServer.setPassword(jsonParmData.get("sourcePassword")
						.getAsString());
			}
			ftpServer.setFileDir(jsonParmData.get("sourceFilePath")
					.getAsString());

			boolean isDelFile = jsonParmData.get("sourceIsDelFile")
					.getAsBoolean();
			if (isDelFile) {
				ftpServer
						.setIfDelSource(FtpSourceFileHanderType.DELETE.ValueCode);
			} else {
				ftpServer
						.setIfDelSource(FtpSourceFileHanderType.UNDELETE.ValueCode);
			}
			
			boolean passiveMode = jsonParmData.get("sourcePassiveMode")
					.getAsBoolean();
			if (passiveMode) {
				ftpServer
						.setPassiveMode(FtpPassiveMode.ISPASSIVEMODE.ValueCode);
			} else {
				ftpServer
						.setPassiveMode(FtpPassiveMode.UNPASSIVEMODE.ValueCode);
			}
			
			String matchMode = jsonParmData.get("matchMode").getAsString();
			String sourceFileName = jsonParmData.get("sourceFileName").getAsString();
			
			if(StringUtils.isNotBlank(sourceFileName)){
				//有匹配
				if(StringUtils.equals(matchMode, "名称匹配")){
					//匹配文件名
					ftpServer.setFileName("{\"filterType\":\"2\",\"checkStr\": \"" + sourceFileName + "\"}");
				}else if(StringUtils.equals(matchMode, "正则匹配")){
					//正则表达式
					ftpServer.setFileName("{\"filterType\":\"1\",\"checkStr\": \"" + sourceFileName + "\"}");
				}
			}else{
				//无匹配
				ftpServer.setFileName("");
			}
			
			ftpServer.setServerCode(jsonParmData.get("sourceFtpServerCode").getAsString());
			ftpServer.setHostType(FtpHostType.SOURCE_HOST.ValueCode);
			ftpServer.setFtp(ftp);
			ftpServerRepository.save(Arrays.asList(ftpServer));

		}

		// 设置目标主机信息
		JsonArray jsonArrayDes = jsonData.get("desDatas").getAsJsonArray();

		for (int i = 0; i < jsonArrayDes.size(); i++) {
			JsonObject jsonParmData = jsonArrayDes.get(i).getAsJsonObject();
			FtpServer ftpServer = new FtpServer();
			FieldSystem system = fieldSystemRepository.findOne(FieldSystem
					.idSpecification(jsonParmData.get("fieldSystemId")
							.getAsString()));
			ftpServer.setOwnFieldSystem(system);
			ftpServer.setHost(jsonParmData.get("desHost").getAsString());
			ftpServer.setPort(jsonParmData.get("desHostPort").getAsString());
			boolean isAnonymous = jsonParmData.get("desIsAnmous")
					.getAsBoolean();
			if (isAnonymous) {
				// 匿名
				ftpServer.setIfAnonymous(FtpAccessType.ANONYMOUS.ValueCode);
				ftpServer.setUserName(Constants.FTP_ANONYMOUS_NAME);
			} else {
				// 非匿名
				ftpServer.setIfAnonymous(FtpAccessType.UNANONYMOUS.ValueCode);
				ftpServer.setUserName(jsonParmData.get("desUserName")
						.getAsString());
				ftpServer.setPassword(jsonParmData.get("desPassword")
						.getAsString());
			}
			ftpServer.setFileDir(jsonParmData.get("desFilePath").getAsString());

			boolean isCoverFile = jsonParmData.get("desIsCoverFile")
					.getAsBoolean();
			if (isCoverFile) {
				ftpServer.setIfCover(FtpTargetFileHanderType.COVER.ValueCode);
			} else {
				ftpServer.setIfCover(FtpTargetFileHanderType.UNCOVER.ValueCode);
			}

			boolean passiveMode = jsonParmData.get("desPassiveMode")
					.getAsBoolean();
			if (passiveMode) {
				ftpServer
						.setPassiveMode(FtpPassiveMode.ISPASSIVEMODE.ValueCode);
			} else {
				ftpServer
						.setPassiveMode(FtpPassiveMode.UNPASSIVEMODE.ValueCode);
			}
			ftpServer.setServerCode(jsonParmData.get("desFtpServerCode").getAsString());
			
			ftpServer.setHostType(FtpHostType.TARGET_HOST.ValueCode);
			ftpServer.setFtp(ftp);
			ftpServerRepository.save(Arrays.asList(ftpServer));

		}
		
		// 记录用户操作日志
		userLogService.save(UserLogOpt.MaintenanceServiceRegister, null, String
				.format("注册了“%s”接口", jsonData.get("interfaceName")
						.getAsString()));
		return true;
	}

	/**
	 * ftp接口更新
	 * 
	 * @param interfaceDatas
	 *            表单数据
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 */
	public boolean ftpServiceUpdate(String interfaceDatas)
			throws ServiceHandlerException {
		// 将表单数据转成json对象
		JsonObject jsonData = GsonUtil.getDefaultJsonParser()
				.parse(interfaceDatas).getAsJsonObject().get("interfaceDatas")
				.getAsJsonObject();
		
		Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(jsonData.get("id")
				.getAsString()));
		
		Ftp sourceFtp = new Ftp();
		BeanUtils.copyProperties(ftp, sourceFtp);
		String code = ftp.getInterfacecode();
		//保存原接口信息
		if(backUpFtpMap.containsKey(ftp.getInterfacecode())){
			backUpFtpMap.remove(ftp.getInterfacecode());
		}
		backUpFtpMap.put(ftp.getInterfacecode(), sourceFtp);
		/*backUpRelationMap.clear();
		backUpRelationMap.put("ftpServer", ftp.getFtpServers());
		backUpRelationMap.put("ftpSchedule", ftp.getIfSchedules());*/
		
		Set<FtpServer> sourceFtpServer = new HashSet<FtpServer>();
		
		Set<FtpServer> ftpserver1 = sourceFtp.getFtpServers();
		for (FtpServer ftpServer : ftpserver1) {
			FtpServer ftpServerN = new FtpServer();
			BeanUtils.copyProperties(ftpServer, ftpServerN);
			sourceFtpServer.add(ftpServerN);
		}
		
		Set<IfSchedule> sourceIfSchedule = new HashSet<IfSchedule>();
		
		Set<IfSchedule> IfSchedule1 = sourceFtp.getIfSchedules();
		for (IfSchedule ifSchedule : IfSchedule1) {
			IfSchedule ifScheduleN = new IfSchedule();
			BeanUtils.copyProperties(ifSchedule, ifScheduleN);
			sourceIfSchedule.add(ifScheduleN);
		}
		
		
		
		Set<FtpServer> updateFtpServer = new HashSet<FtpServer>();
		Set<IfSchedule> updateIfSchedule = new HashSet<IfSchedule>();
		updateFtpService(jsonData, ftp, updateFtpServer, updateIfSchedule);
		boolean ftpRouteChanged = jsonData.get("ftpRouteChanged").getAsBoolean();
		if(StringUtils.equals(ftp.getAuditStatus(), AuditStatusType.AUDITED.ValueCode) && ftpRouteChanged && StringUtils.equals(ftp.getStatus(), EnableType.ENABLE.ValueCode)){
			//已审核，调用接口更新ftp路由
			// 测试servicemix服务器是否可以连通
			try {
				ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
			} catch (ServerMixException e) {
				//手动回滚事务
				ftpServerRepository.delete(updateFtpServer);
				ifScheduleRepository.delete(updateIfSchedule);
				ftpRepository.delete(Arrays.asList(ftp));
				
				//重新保存ftp接口
				reSaveFtp(code, backUpFtpMap, sourceFtpServer, sourceIfSchedule);
				throw new ServiceHandlerException(e.getMessage(),
						CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
			}
			try{
				boolean isSchedule = jsonData.get("isSchedule").getAsBoolean();
				boolean status = false;
				if(isSchedule){
					status = FtpRouteHandleUtil.process(Constants.RESTART_CAMEL, ftp.getInterfacecode());
				}else{
					status = FtpRouteHandleUtil.process(Constants.DEL_CAMEL, ftp.getInterfacecode());
				}
				if(!status){
					throw new ServiceHandlerException(CommonUtils.MSG_UPDATE_FTP_RETOUTER_FAIED, 
							CommonUtils.CODE_UPDATE_FTP_RETOUTER_FAIED);
				}
				
			}catch(Exception e){
				//手动回滚事务
				ftpServerRepository.delete(updateFtpServer);
				ifScheduleRepository.delete(updateIfSchedule);
				ftpRepository.delete(Arrays.asList(ftp));
				
				//重新保存ftp接口
				reSaveFtp(code, backUpFtpMap, sourceFtpServer, sourceIfSchedule);
				throw new ServiceHandlerException(CommonUtils.MSG_UPDATE_FTP_RETOUTER_FAIED, 
						CommonUtils.CODE_UPDATE_FTP_RETOUTER_FAIED);
			}
		}
		
		// 记录用户操作日志
		userLogService.save(UserLogOpt.MaintenanceBusinessServiceManagement, null,
				String.format("更新了“%s”接口", jsonData.get("interfaceName").getAsString()));
		return true;
	}

	
	public void reSaveFtp(String code, Map<String, Ftp> ftpMap, Set<FtpServer> sourceFtpServer, Set<IfSchedule> sourceIfSchedule){
		Ftp backUpFtp = ftpMap.get(code);
		if(backUpFtp != null){
			Ftp upFtp = new Ftp();
			
			//upFtp.setId(backUpFtp.getId());
			upFtp.setInterfacecode(backUpFtp.getInterfacecode());
			upFtp.setIfPublic(backUpFtp.getIfPublic());
			// 设置接口可见范围
			if (StringUtils.equals(backUpFtp.getIfPublic(),
					InterfaceIsPublicType.PRIVATE.ValueCode)) {
				upFtp.getVisibleFieldSystems().clear();
				upFtp.getVisibleFieldSystems().addAll(backUpFtp.getVisibleFieldSystems());
			}
			
			upFtp.setType(IfType.FTP.ValueCode);
			upFtp.setInterfaceName(backUpFtp.getInterfaceName());
			upFtp.setVersion(backUpFtp.getVersion());
			upFtp.setDesc(backUpFtp.getDesc());
			upFtp.setOvertime(backUpFtp.getOvertime());
			upFtp.setAuditStatus(backUpFtp.getAuditStatus());
			upFtp.setIfCost(IfCostType.FREE.ValueCode);
			upFtp.setStatus(backUpFtp.getStatus());
			upFtp.setIsEnable(backUpFtp.getIsEnable());
			
			upFtp.setFieldSystem(backUpFtp.getFieldSystem());
			upFtp.setSystemCode(backUpFtp.getFieldSystem().getCode());
			
			upFtp.setIsSchedule(backUpFtp.getIsSchedule());
			
			upFtp.setFileCachePath("./temp/" + backUpFtp.getInterfaceName());
			ftpRepository.save(Arrays.asList(upFtp));
			
			//设置调度信息
			if(StringUtils.equals(backUpFtp.getIsSchedule(), ScheduleType.SCHEDULE.ValueCode)){
				for (IfSchedule backUpIfSchedule : sourceIfSchedule) {
					IfSchedule upIfSchedule = new IfSchedule();
					
					//upIfSchedule.setId(backUpIfSchedule.getId());
					upIfSchedule.setName(backUpIfSchedule.getName());
					upIfSchedule.setIfType(IfType.FTP.ValueCode);
					upIfSchedule.setBeginTime(backUpIfSchedule.getBeginTime());
					upIfSchedule.setEndTime(backUpIfSchedule.getEndTime());
					

					upIfSchedule.setRunWay(backUpIfSchedule.getRunWay());
					upIfSchedule.setRunCyc(backUpIfSchedule.getRunCyc());
					upIfSchedule.setDayOfWeek(backUpIfSchedule.getDayOfWeek());
					upIfSchedule.setFtp(upFtp);
					ifScheduleRepository.save(Arrays.asList(upIfSchedule));
				}
			}else{
				
			}
			
			// 设置源主机信息
			for (FtpServer backUpFtpServer : sourceFtpServer) {
				FtpServer upFtpServer = new FtpServer();
				
				//upFtpServer.setId(backUpFtpServer.getId());
				upFtpServer.setOwnFieldSystem(backUpFtpServer.getOwnFieldSystem());
				upFtpServer.setHost(backUpFtpServer.getHost());
				upFtpServer.setPort(backUpFtpServer.getPort());
				if (StringUtils.equals(backUpFtpServer.getIfAnonymous(), FtpAccessType.ANONYMOUS.ValueCode)) {
					// 匿名
					upFtpServer.setIfAnonymous(FtpAccessType.ANONYMOUS.ValueCode);
					//upFtpServer.setUserName(Constants.FTP_ANONYMOUS_NAME);
				} else {
					// 非匿名
					upFtpServer.setIfAnonymous(FtpAccessType.UNANONYMOUS.ValueCode);
					upFtpServer.setUserName(backUpFtpServer.getUserName());
					upFtpServer.setPassword(backUpFtpServer.getPassword());
				}
				upFtpServer.setFileDir(backUpFtpServer.getFileDir());
				if(StringUtils.equals(backUpFtpServer.getHostType(), FtpHostType.SOURCE_HOST.ValueCode)){
					//源主机
					upFtpServer.setHostType(FtpHostType.SOURCE_HOST.ValueCode);
					upFtpServer.setIfDelSource(backUpFtpServer.getIfDelSource());
				}else{
					//目标主机
					upFtpServer.setHostType(FtpHostType.TARGET_HOST.ValueCode);
					upFtpServer.setIfCover(backUpFtpServer.getIfCover());
				}
				upFtpServer.setFileName(backUpFtpServer.getFileName());
				upFtpServer.setFtp(upFtp);
				ftpServerRepository.save(Arrays.asList(upFtpServer));
			}
		}
	}
	
	
	@Transactional
	public void updateFtpService(JsonObject jsonData, Ftp ftp, Set<FtpServer> updateFtpServerSet, Set<IfSchedule> updateIfScheduleSet){
		String shedule = ftp.getIsSchedule();
		// 设置接口可见范围
		List<String> fieldSystemIds = new ArrayList<>();
		String isPublic = jsonData.get("isPublic").getAsString();
		ftp.setIfPublic(isPublic);
		if (StringUtils.equals(isPublic,
				InterfaceIsPublicType.PRIVATE.ValueCode)) {
			JsonArray object = jsonData.get("fieldSystemIds").getAsJsonArray();
			for (int i = 0; i < object.size(); i++) {
				fieldSystemIds.add(object.get(i).getAsString());
			}
			List<FieldSystem> fieldSystems = fieldSystemRepository
					.findAll(fieldSystemIds);
			ftp.getVisibleFieldSystems().clear();
			ftp.getVisibleFieldSystems().addAll(fieldSystems);
		}

		ftp.setType(IfType.FTP.ValueCode);
		ftp.setInterfaceName(jsonData.get("interfaceName").getAsString());
		ftp.setVersion(jsonData.get("interfaceVersion").getAsString());
		ftp.setDesc(jsonData.get("interfaceDes").getAsString());
		ftp.setOvertime(jsonData.get("overTimeSetting").getAsString());

		FieldSystem fieldSystem = fieldSystemRepository.findOne(FieldSystem
				.idSpecification(jsonData.get("systemId").getAsString()));
		ftp.setFieldSystem(fieldSystem);
		ftp.setSystemCode(fieldSystem.getCode());

		boolean isSchedule = jsonData.get("isSchedule").getAsBoolean();
		if(isSchedule){
			ftp.setIsSchedule(ScheduleType.SCHEDULE.ValueCode);
		}else{
			ftp.setIsSchedule(ScheduleType.UNSCHEDULE.ValueCode);
		}
		
		/*ftp.setFileCachePath(jsonData.get("fileCachePath").getAsString());*/
		
		ftpRepository.save(Arrays.asList(ftp));

		IfSchedule ifSchedule = null;
		if(StringUtils.equals(shedule, ScheduleType.SCHEDULE.ValueCode)){
			ifSchedule = ifScheduleRepository.findOne(IfSchedule
					.idSpecification(jsonData.get("ifScheduleId").getAsString()));
		}
		if (isSchedule) {
			// 修改ftp接口调度信息
			if(ifSchedule == null){
				ifSchedule = new IfSchedule();
			}
			ifSchedule.setName(jsonData.get("interfaceName").getAsString());
			ifSchedule.setIfType(IfType.FTP.ValueCode);
			try {
				ifSchedule.setBeginTime(fastDateFormat1.parse(jsonData.get("beginTime").getAsString()));
				ifSchedule.setEndTime(fastDateFormat1.parse(jsonData.get("endTime").getAsString()));
			} catch (ParseException e) {
				e.printStackTrace();
			}

			ifSchedule.setRunWay(jsonData.get("runWay").getAsString());
			ifSchedule.setRunCyc(Integer.parseInt(jsonData.get("runCyc").getAsString()));
			ifSchedule.setDayOfWeek(jsonData.get("dayOfWeek").getAsString());
			/*
			 * ifSchedule
			 * .setFileCachePath(jsonData.get("fileCachePath").getAsString());
			 */
			ifSchedule.setFtp(ftp);
			ifScheduleRepository.save(Arrays.asList(ifSchedule));
			updateIfScheduleSet.add(ifSchedule);
		} else {
			if(ifSchedule == null){
				
			}else{
				ifScheduleRepository.delete(ifSchedule);
			}
		}

		
		// 获取要删除的主机信息进行删除操作
		JsonElement delParamIds = jsonData.get("deleteHostIds");
		if (delParamIds != null) {
			JsonArray objectParams = jsonData.get("deleteHostIds").getAsJsonArray();
			for (int i = 0; i < objectParams.size(); i++) {
				if(StringUtils.isNotBlank(objectParams.get(i).getAsString())){
					ftpServerRepository.delete(objectParams.get(i).getAsString());
				}
			}
		}

		// 修改源主机信息
		JsonArray jsonArraySource = jsonData.get("sourceDatas")
				.getAsJsonArray();

		for (int i = 0; i < jsonArraySource.size(); i++) {
			JsonObject jsonParmData = jsonArraySource.get(i).getAsJsonObject();
			FtpServer ftpServer = ftpServerRepository.findOne(FtpServer
					.idSpecification(jsonParmData.get("sourceHostId")
							.getAsString()));
			if (ftpServer == null) {
				ftpServer = new FtpServer();
			}
			ftpServer.setHost(jsonParmData.get("sourceHost").getAsString());
			ftpServer.setPort(jsonParmData.get("sourceHostPort").getAsString());
			boolean isAnonymous = jsonParmData.get("sourceIsAnmous")
					.getAsBoolean();
			if (isAnonymous) {
				ftpServer.setIfAnonymous(FtpAccessType.ANONYMOUS.ValueCode);
				ftpServer.setUserName(Constants.FTP_ANONYMOUS_NAME);
			} else {
				ftpServer.setIfAnonymous(FtpAccessType.UNANONYMOUS.ValueCode);
				ftpServer.setUserName(jsonParmData.get("sourceUserName")
						.getAsString());
				ftpServer.setPassword(jsonParmData.get("sourcePassword")
						.getAsString());
			}
			ftpServer.setFileDir(jsonParmData.get("sourceFilePath")
					.getAsString());

			boolean isDelFile = jsonParmData.get("sourceIsDelFile")
					.getAsBoolean();
			if (isDelFile) {
				ftpServer
						.setIfDelSource(FtpSourceFileHanderType.DELETE.ValueCode);
			} else {
				ftpServer
						.setIfDelSource(FtpSourceFileHanderType.UNDELETE.ValueCode);
			}
			boolean passiveMode = jsonParmData.get("sourcePassiveMode")
					.getAsBoolean();
			if (passiveMode) {
				ftpServer
						.setPassiveMode(FtpPassiveMode.ISPASSIVEMODE.ValueCode);
			} else {
				ftpServer
						.setPassiveMode(FtpPassiveMode.UNPASSIVEMODE.ValueCode);
			}
			FieldSystem system = fieldSystemRepository.findOne(FieldSystem
					.idSpecification(jsonParmData.get("fieldSystemId")
							.getAsString()));
			ftpServer.setOwnFieldSystem(system);
			String matchMode = jsonParmData.get("matchMode").getAsString();
			String sourceFileName = jsonParmData.get("sourceFileName").getAsString();
			if(StringUtils.isNotBlank(sourceFileName)){
				//有匹配
				if(StringUtils.equals(matchMode, "名称匹配")){
					//匹配文件名
					ftpServer.setFileName("{\"filterType\":\"2\",\"checkStr\": \"" + sourceFileName + "\"}");
				}else if(StringUtils.equals(matchMode, "正则匹配")){
					//正则表达式
					ftpServer.setFileName("{\"filterType\":\"1\",\"checkStr\": \"" + sourceFileName + "\"}");
				}
			}else{
				//无匹配
				ftpServer.setFileName("");
			}
			
			/*ftpServer.setFileName(jsonParmData.get("sourceFileName")
					.getAsString());*/
			ftpServer.setServerCode(jsonParmData.get("sourceFtpServerCode").getAsString());
			ftpServer.setHostType(FtpHostType.SOURCE_HOST.ValueCode);
			ftpServer.setFtp(ftp);
			ftpServerRepository.save(Arrays.asList(ftpServer));
			
			updateFtpServerSet.add(ftpServer);
		}

		// 修改目标主机信息
		JsonArray jsonArrayDes = jsonData.get("desDatas").getAsJsonArray();

		for (int i = 0; i < jsonArrayDes.size(); i++) {
			JsonObject jsonParmData = jsonArrayDes.get(i).getAsJsonObject();
			FtpServer ftpServer = ftpServerRepository.findOne(FtpServer
					.idSpecification(jsonParmData.get("desHostId")
							.getAsString()));
			if (ftpServer == null) {
				ftpServer = new FtpServer();
			}

			ftpServer.setHost(jsonParmData.get("desHost").getAsString());
			ftpServer.setPort(jsonParmData.get("desHostPort").getAsString());
			boolean isAnonymous = jsonParmData.get("desIsAnmous")
					.getAsBoolean();
			if (isAnonymous) {
				ftpServer.setIfAnonymous(FtpAccessType.ANONYMOUS.ValueCode);
				ftpServer.setUserName(Constants.FTP_ANONYMOUS_NAME);
			} else {
				ftpServer.setIfAnonymous(FtpAccessType.UNANONYMOUS.ValueCode);
				ftpServer.setUserName(jsonParmData.get("desUserName")
						.getAsString());
				ftpServer.setPassword(jsonParmData.get("desPassword")
						.getAsString());
			}
			ftpServer.setFileDir(jsonParmData.get("desFilePath").getAsString());

			boolean isCoverFile = jsonParmData.get("desIsCoverFile")
					.getAsBoolean();
			if (isCoverFile) {
				ftpServer.setIfCover(FtpTargetFileHanderType.COVER.ValueCode);
			} else {
				ftpServer.setIfCover(FtpTargetFileHanderType.UNCOVER.ValueCode);
			}
			
			boolean passiveMode = jsonParmData.get("desPassiveMode")
					.getAsBoolean();
			if (passiveMode) {
				ftpServer
						.setPassiveMode(FtpPassiveMode.ISPASSIVEMODE.ValueCode);
			} else {
				ftpServer
						.setPassiveMode(FtpPassiveMode.UNPASSIVEMODE.ValueCode);
			}
			FieldSystem system = fieldSystemRepository.findOne(FieldSystem
					.idSpecification(jsonParmData.get("fieldSystemId")
							.getAsString()));
			ftpServer.setOwnFieldSystem(system);
			ftpServer.setHostType(FtpHostType.TARGET_HOST.ValueCode);
			ftpServer.setServerCode(jsonParmData.get("desFtpServerCode").getAsString());
			ftpServer.setFtp(ftp);
			ftpServerRepository.save(Arrays.asList(ftpServer));
			
			updateFtpServerSet.add(ftpServer);
		}
		
	}
	/**
	 * 更新接口状态
	 * 
	 * @param id
	 *            接口的ID
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 */
	@Transactional
	public boolean updateInterfaceStatus(String id)
			throws ServiceHandlerException {
		Http http = httpRepository.findOne(Http.idSpecification(id));
		if (http != null) {
			if (StringUtils.equals(http.getStatus(),
					IfStatusType.ENABLE.ValueCode)) {
				http.setStatus(IfStatusType.DISABLE.ValueCode);
				// 停用
				if (StringUtils.equals(http.getBundleType(),
						BundleModeType.CUSTOM.ValueCode)) {
					updateBundleStatus(http.getType(),
							http.getDefinedbundles(), Constants.STOP);
				}
			} else if (StringUtils.equals(http.getStatus(),
					IfStatusType.DISABLE.ValueCode)) {
				http.setStatus(IfStatusType.ENABLE.ValueCode);
				// 启用
				if (StringUtils.equals(http.getBundleType(),
						BundleModeType.CUSTOM.ValueCode)) {
					updateBundleStatus(http.getType(),
							http.getDefinedbundles(), Constants.START);
				}
			}

			httpRepository.save(Arrays.asList(http));
			// 更新Redis中对应的数据
			updateHttpRedisData(http);
			// 记录用户操作日志
			userLogService.save(
					UserLogOpt.MaintenanceBusinessServiceManagement, null,
					String.format("更新了“%s”接口的状态", http.getName()));
			return true;
		} else {
			Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(id));
			if (StringUtils.equals(ftp.getStatus(),
					IfStatusType.ENABLE.ValueCode)) {
				ftp.setStatus(IfStatusType.DISABLE.ValueCode);
				ftpRepository.save(Arrays.asList(ftp));
				// 停用
				/*updateBundleStatus(ftp.getType(), ftp.getDefinedbundles(),
						Constants.STOP);*/
			} else if (StringUtils.equals(ftp.getStatus(),
					IfStatusType.DISABLE.ValueCode)) {
				ftp.setStatus(IfStatusType.ENABLE.ValueCode);
				ftpRepository.save(Arrays.asList(ftp));
				// 启用
				/*updateBundleStatus(ftp.getType(), ftp.getDefinedbundles(),
						Constants.START);*/
			}

			// 记录用户操作日志
			userLogService.save(
					UserLogOpt.MaintenanceBusinessServiceManagement, null,
					String.format("更新了“%s”接口的状态", ftp.getInterfaceName()));
			return true;
		}
	}

	/**
	 * 接口审核
	 * 
	 * @param id
	 *            接口ID
	 * @param interfaceType
	 *            接口类型呢
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 */
	@Transactional
	public boolean updateInterfaceAuditStatus(String id, String interfaceType)
			throws ServiceHandlerException {
		if (StringUtils.equals(interfaceType, IfType.FTP.ValueCode)) {
			// FTP接口审核
			Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(id));
			ftp.setAuditStatus(AuditStatusType.AUDITED.ValueCode);
			ftp.setStatus(IfStatusType.ENABLE.ValueCode);
			/*Set<DefinedBundle> definedBundles = ftp.getDefinedbundles();

			AuditFtpInterface(ftp, definedBundles);*/
			ftpRepository.save(Arrays.asList(ftp));
		} else {
			// HTTP接口审核
			Http http = httpRepository.findOne(Http.idSpecification(id));
			http.setAuditStatus(AuditStatusType.AUDITED.ValueCode);
			http.setStatus(IfStatusType.ENABLE.ValueCode);

			if (StringUtils.equals(http.getBundleType(),
					BundleModeType.CUSTOM.ValueCode)) {
				Set<DefinedBundle> definedBundles = http.getDefinedbundles();
				AuditHttpInterface(http, definedBundles);
			} else {
				httpRepository.save(Arrays.asList(http));
				// 更新Redis中对应的数据
				updateHttpRedisData(http);
			}
			// 记录用户操作日志
			userLogService.save(UserLogOpt.MaintenanceServiceVerify, null,
					String.format("审核了“%s”接口", http.getName()));
		}

		return true;
	}
	
	
	
	//批量审核http接口
	public void batchAuditHttpIfs(Map<String,String> handleResutlMap, MultiKeyMap<String, User> sendEmailMap, String httpIds){
		if(httpIds.contains(",")){
			//两个或两个以上
			String[] ids = httpIds.split(",");
			for (String id : ids) {
				auditHttpIf(handleResutlMap, sendEmailMap, id);
			}
		}else{
			//只有一个
			auditHttpIf(handleResutlMap, sendEmailMap, httpIds);
		}
			
	}
	
	//审核http接口
	public void auditHttpIf(Map<String,String> handleResutlMap, MultiKeyMap<String, User> sendEmailMap, String id){
		String ifName = "";
		User user = null;
		try{
			Http http = httpRepository.findOne(Http.idSpecification(id));
			ifName = http.getName();
			user = userRepository.findByUserCode(http.getCreator());
			http.setAuditStatus(AuditStatusType.AUDITED.ValueCode);
			http.setStatus(IfStatusType.ENABLE.ValueCode);

			if (StringUtils.equals(http.getBundleType(),
					BundleModeType.CUSTOM.ValueCode)) {
				Set<DefinedBundle> definedBundles = http.getDefinedbundles();
				AuditHttpInterface(http, definedBundles);
			} else {
				// 更新Redis中对应的数据
				updateHttpRedisData(http);
				httpRepository.save(Arrays.asList(http));
			}
			//获取成功处理的接口
			handleResutlMap.put(ifName, "审核成功！");
			
			//获取处理正常的接口邮箱
			sendEmailMap.put(ifName, "1", user);
		}catch(Exception e){
			e.printStackTrace();
			//获取处理出现异常的接口
			handleResutlMap.put(ifName, "审核失败！");
			
			//获取处理正常的接口邮箱
			sendEmailMap.put(ifName, "0", user);
		}
		 
	}
	
	//批量审核ftp接口
	public void batchAuditFtpIfs(Map<String,String> handleResutlMap, MultiKeyMap<String, User> sendEmailMap, String ftpIds){
		if(ftpIds.contains(",")){
			//两个或两个以上
			String[] ids = ftpIds.split(",");
			for (String id : ids) {
				auditFtpIf(handleResutlMap, sendEmailMap, id);
			}
		}else{
			//只有一个
			auditFtpIf(handleResutlMap, sendEmailMap, ftpIds);
		}
	}
	
	// 审核ftp接口
	public void auditFtpIf(Map<String,String> handleResutlMap, MultiKeyMap<String, User> sendEmailMap, String id) {
		String ifName = "";
		User user = null;
		Ftp ftp = null;
		try {
			ftp = ftpRepository.findOne(Ftp.idSpecification(id));
			ifName = ftp.getInterfaceName();
			user = userRepository.findByUserCode(ftp.getCreator());
			ftp.setAuditStatus(AuditStatusType.AUDITED.ValueCode);
			ftp.setStatus(IfStatusType.ENABLE.ValueCode);
			ftpRepository.save(Arrays.asList(ftp));
			//调用cookCamelFtp接口创建ftp路由并执行
			callCamelFtpIf(ftp);
			
			//获取成功处理的接口
			handleResutlMap.put(ifName, "审核成功！");
			
			//获取处理正常的接口邮箱
			sendEmailMap.put(ifName, "1", user);
		} catch (ServiceHandlerException e) {
			e.printStackTrace();
			//回滚事务处理
			ftp.setAuditStatus(AuditStatusType.UNAUDITED.ValueCode);
			ftp.setStatus(IfStatusType.DISABLE.ValueCode);
			ftpRepository.save(Arrays.asList(ftp));
			//获取处理出现异常的接口
			handleResutlMap.put(ifName, "审核失败！");
			
			//获取处理异常的接口邮箱
			sendEmailMap.put(ifName, "0", user);
		} catch (Exception e){
			e.printStackTrace();
			//获取处理出现异常的接口
			handleResutlMap.put(ifName, "审核失败！");
			
			//获取处理异常的接口邮箱
			sendEmailMap.put(ifName, "0", user);
		}
		

	}
	
	
	//调用cookCamelFtp
	public void callCamelFtpIf(Ftp ftp){
		// 测试servicemix服务器是否可以连通
		try {
			ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
		} catch (ServerMixException e) {
			throw new ServiceHandlerException(e.getMessage(),
					CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
		}
		
		boolean status = FtpRouteHandleUtil.process(Constants.RESTART_CAMEL, ftp.getInterfacecode());
		if(!status){
			throw new ServiceHandlerException(CommonUtils.MSG_CREATE_FTP_RETOUTER_FAIED, 
					CommonUtils.CODE_CREATE_FTP_RETOUTER_FAIED);
		}
	}

	/**
	 * 报文管理
	 * 
	 * @param interfaceDatas
	 *            表单数据
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 * @throws NoSuchObjectException 
	 */
	@Transactional
	public boolean updateIfMessage(String interfaceDatas)
			throws ServiceHandlerException, NoSuchObjectException {
		JsonObject jsonData = GsonUtil.getDefaultJsonParser()
				.parse(interfaceDatas).getAsJsonObject().get("interfaceDatas")
				.getAsJsonObject();

		Http http = httpRepository.findOne(Http.idSpecification(jsonData.get(
				"id").getAsString()));
		http.setRequestMess(jsonData.get("requestMess").getAsString());
		http.setReturnMess(jsonData.get("returnMess").getAsString());

		JsonArray objectParams = jsonData.get("deleteParamIds")
				.getAsJsonArray();
		for (int i = 0; i < objectParams.size(); i++) {
			if(StringUtils.isNotBlank(objectParams.get(i).getAsString())){
				interfaceParameterRepository.delete(objectParams.get(i)
						.getAsString());
			}
		}

		String transportProtocol = TransportProtocolType.get(http.getTransportProtocol()).ValueName;

		ParamSetting paramSetting = paramSettingReppository
				.findByParamName(Constants.SERVERADDRESS);
		
		if (StringUtils.equals(http.getType(), IfType.REST.ValueCode)) {
			//rest
			if(StringUtils.equals(http.getRequest(), IfReqType.GET.ValueCode)){
				//GET请求
				String resultStr = "";
				// 获取接口请求参数并保存
				StringBuilder queryString = new StringBuilder();
				JsonArray jsonReqArray = jsonData.get("requestParameters").getAsJsonArray();
				if(jsonReqArray.size() > 0){
					for (int i = 0; i < jsonReqArray.size(); i++) {
						JsonObject jsonParmData = jsonReqArray.get(i).getAsJsonObject();
						String paramName = jsonParmData.get("reqParameterName").getAsString();
						String paramDefaultValue = jsonParmData.get("reqParameterDefaultValue").getAsString();
						String resutlString = paramName + "=" + paramDefaultValue + "&";
						queryString.append(resutlString);
					}
						
					resultStr = queryString.toString().substring(0, queryString.length() - 1);
					//有参数
					http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
							+ "/" + http.getSystemCode() + "/"
							+ http.getVersion() + "/"
							+ http.getCode() + "/" + resultStr);
				}else{
					http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
					+ "/" + http.getSystemCode() + "/"
					+ http.getVersion() + "/"
					+ http.getCode() + "/");
				}
				
				http.setRequest(IfReqType.GET.ValueCode);
			}else{
				//POST请求
				http.setPubUrl(transportProtocol + "://" + paramSetting.getParamValue()
				+ "/" + http.getSystemCode() + "/"
				+ http.getVersion() + "/"
				+ http.getCode() + "/");
				
				http.setRequest(IfReqType.POST.ValueCode);
			}
		}
		// 获取接口请求参数进行保存
		JsonArray jsonReqArray = jsonData.get("requestParameters")
				.getAsJsonArray();

		for (int i = 0; i < jsonReqArray.size(); i++) {
			JsonObject jsonParmData = jsonReqArray.get(i).getAsJsonObject();
			IfParameter interfaceParameter = interfaceParameterRepository
					.findOne(IfParameter.idSpecification(jsonParmData.get(
							"reqParamId").getAsString()));
			if (interfaceParameter == null) {
				interfaceParameter = new IfParameter();
			}
			interfaceParameter.setName(jsonParmData.get("reqParameterName")
					.getAsString());
			interfaceParameter.setDataType(jsonParmData.get(
					"comboxReqParameterType").getAsString());
			interfaceParameter.setDefaultValue(jsonParmData.get(
					"reqParameterDefaultValue").getAsString());
			interfaceParameter.setIsNeed(jsonParmData.get("reqParameterIsMust")
					.getAsString());
			interfaceParameter.setDesc(jsonParmData.get("reqParameterDes")
					.getAsString());
			interfaceParameter.setHttp(http);
			interfaceParameter.setType(ParameterType.REQUEST.ValueCode);
			interfaceParameter.setIsEnable(EnableType.ENABLE.ValueCode);

			interfaceParameterRepository
					.save(Arrays.asList(interfaceParameter));

		}

		// 获取接口返回参数进行保存
		JsonArray jsonRepArray = jsonData.get("responseParameters")
				.getAsJsonArray();

		for (int i = 0; i < jsonRepArray.size(); i++) {
			JsonObject jsonParmData = jsonRepArray.get(i).getAsJsonObject();
			IfParameter interfaceParameter = interfaceParameterRepository
					.findOne(IfParameter.idSpecification(jsonParmData.get(
							"repParamId").getAsString()));
			if (interfaceParameter == null) {
				interfaceParameter = new IfParameter();
			}

			interfaceParameter.setName(jsonParmData.get("repParameterName")
					.getAsString());
			interfaceParameter.setDataType(jsonParmData.get(
					"comboxRepParameterType").getAsString());
			interfaceParameter.setIsNeed("0");
			interfaceParameter.setDesc(jsonParmData.get("repParameterDes")
					.getAsString());
			interfaceParameter.setHttp(http);
			interfaceParameter.setType(ParameterType.RETURN.ValueCode);
			interfaceParameter.setIsEnable(EnableType.ENABLE.ValueCode);

			interfaceParameterRepository
					.save(Arrays.asList(interfaceParameter));

		}

		httpRepository.save(Arrays.asList(http));
		// 更新Redis中的对应数据
		updateHttpRedisData(http);
		// 记录用户操作日志
		userLogService.save(UserLogOpt.MaintenanceMessageManagement, null,
				String.format("更新了“%s”接口的请求报文", http.getName()));
		return true;
	}

	/**
	 * 接口卸载
	 * 
	 * @param id
	 *            接口ID
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 */
	@Transactional
	public boolean interfaceUninstall(String id) throws ServiceHandlerException {
		// 测试服务器是否可以连通
		try {
			ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
		} catch (ServerMixException e) {
			throw new ServiceHandlerException(e.getMessage(),
					CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
		}

		List<MonitorService> monitorServers = eSBServerFactory
				.getMonitorService();

		Http http = httpRepository.findOne(Http.idSpecification(id));
		if (http != null) {
			if (StringUtils.equals(http.getBundleType(),BundleModeType.CUSTOM.ValueCode)) {

				if (StringUtils.equals(AuditStatusType.UNAUDITED.ValueCode,http.getAuditStatus())) {
					// 未审核
					// 设置关联表的is_enable为不可用
					settingRelationTableValue(http.getId(), "0");

					http.setIsEnable(EnableType.DISABLE.ValueCode);
				} else {
					// 已审核
					Set<DefinedBundle> definedBundles = http.getDefinedbundles();
					for (DefinedBundle definedBundle : definedBundles) {
						if (StringUtils.equals(definedBundle.getIsDefinedBundle(), "1")) {
							try {
								for (MonitorService monitorService : monitorServers) {
									monitorService.executeBundle(Integer.parseInt(definedBundle.getBundleCode()),"uninstall");
								}
							} catch (Exception e) {
								if (e.getCause() instanceof ConnectException) {
									throw new ServiceHandlerException(
											"卸载失败，"+ CommonUtils.MSG_CONNECT_SERVICEMIX_FAIED,
											CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
								} else {
									throw new ServiceHandlerException(
											"卸载失败，"+ CommonUtils.MSG_CALL_INTERFACES_FAIED,
											CommonUtils.CODE_CALL_INTERFACES_FAIED);
								}
							}
						}
					}
					http.getDefinedbundles().clear();

					// 设置关联表的is_enable为不可用
					settingRelationTableValue(http.getId(), "0");

					http.setIsEnable(EnableType.DISABLE.ValueCode);
				}
			} else {
				// 代理模式
				// 设置关联表的is_enable为不可用
				settingRelationTableValue(http.getId(), "0");
				http.setIsEnable(EnableType.DISABLE.ValueCode);
			}
			httpRepository.save(Arrays.asList(http));
			// 删除Redis中对应的数据
			delHttpRedisData(http);
			// 记录用户操作日志
			userLogService.save(
					UserLogOpt.MaintenanceBusinessServiceManagement, null,
					String.format("卸载了“%s”接口", http.getName()));
			return true;
		} else {
			Ftp ftp = ftpRepository.findOne(Ftp.idSpecification(id));
			if (StringUtils.equals(AuditStatusType.UNAUDITED.ValueCode,
					ftp.getAuditStatus())) {
				ftp.setIsEnable(EnableType.DISABLE.ValueCode);
			} else {
				// 测试servicemix服务器是否可以连通
				try {
					ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
				} catch (ServerMixException e) {
					throw new ServiceHandlerException(e.getMessage(),
							CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
				}
				
				
				try{
					boolean status = FtpRouteHandleUtil.process(Constants.DEL_CAMEL, ftp.getInterfacecode());
					if(!status){
						throw new ServiceHandlerException(CommonUtils.MSG_DEL_FTP_RETOUTER_FAIED, 
								CommonUtils.CODE_DEL_FTP_RETOUTER_FAIED);
					}
					
				}catch(Exception e){
					throw new ServiceHandlerException(CommonUtils.MSG_DEL_FTP_RETOUTER_FAIED, 
							CommonUtils.CODE_DEL_FTP_RETOUTER_FAIED);
				}
				
				ftp.setIsEnable(EnableType.DISABLE.ValueCode);
			}
			ftpRepository.save(Arrays.asList(ftp));
			// 记录用户操作日志
			userLogService.save(
					UserLogOpt.MaintenanceBusinessServiceManagement, null,
					String.format("卸载了“%s”接口", ftp.getInterfaceName()));
			return true;
		}
	}

	/**
	 * 设置接口关联表的记录的is_enable的状态为0
	 * 
	 * @param ifId
	 *            接口ID
	 * @param isEnable
	 *            接口状态
	 */
	public void settingRelationTableValue(String ifId, String isEnable) {
		long count = alarmRepository.countByIfId(ifId);
		if (count > 0) {
			throw new ServiceHandlerException(CommonUtils.MSG_CONNOT_DELETE,
					CommonUtils.CODE_CONNOT_DELETE);
		}

		// 设置token表中的is_enable为0
		String tokenSql = "UPDATE T_ESB_BU_IF_TOKEN SET IS_ENABLE=:isEnable WHERE IF_ID=:ifId";
		Query tokenQuery = entityManager.createNativeQuery(tokenSql);
		tokenQuery.setParameter("isEnable", isEnable);
		tokenQuery.setParameter("ifId", ifId);
		tokenQuery.executeUpdate();

		// 设置请求量的is_enable为0
		String ifReqSql = "UPDATE t_esb_bu_if_request_qty SET IS_ENABLE=:isEnable WHERE IF_ID=:ifId";
		Query ifReqQuery = entityManager.createNativeQuery(ifReqSql);
		ifReqQuery.setParameter("isEnable", isEnable);
		ifReqQuery.setParameter("ifId", ifId);
		ifReqQuery.executeUpdate();

		// 设置可见范围表中的is_enable为0
		String visibleSql = "UPDATE t_esb_bu_if_visiblity SET IS_ENABLE=:isEnable WHERE IF_ID=:ifId";
		Query visibleQuery = entityManager.createNativeQuery(visibleSql);
		visibleQuery.setParameter("isEnable", isEnable);
		visibleQuery.setParameter("ifId", ifId);
		visibleQuery.executeUpdate();
	}

	/**
	 * 根据bundle名称进行删除操作
	 * 
	 * @param bundleName
	 * @return
	 */
	public String bundleDelete(String bundleName) {

		JsonObject result = new JsonObject();
		String proPath = ServiceManagerController.class.getClassLoader()
				.getResource("").getPath();// 得到当前项目的根目录的/bin:E:/eclipse/workspace/Cook-Test/bin/
		String filePath = proPath.substring(0, proPath.length() - 4);// 得到当前项目的根目录:E:/eclipse/workspace/Cook-Test
		File file = new File(filePath + "bundleFile/" + bundleName);
		if (!file.exists()) {
			result.addProperty("backValue", "文件不存在或者文件名错误！！");
		} else {
			file.delete();
			result.addProperty("backValue", "文件删除成功！");
		}

		return result.toString();
	}

	/**
	 * webservice和rest接口更新
	 * 
	 * @param bundles
	 *            接口依赖的包集合
	 * @param object
	 * @param objectIds
	 *            需要更新的接口部署包ID
	 */
	public void httpBundleInfoUpdate(Set<DefinedBundle> bundles,
			JsonArray object, JsonArray objectIds) {
		/*ParamSetting paramSettingBundlePath = paramSettingReppository
				.findByParamName(Constants.SERVER_HANDLE_BUNDLE_PATH);
		JsonArray jsonDatas = GsonUtil.getDefaultJsonParser()
				.parse(paramSettingBundlePath.getParamValue()).getAsJsonArray();*/
		
		ParamSetting paramSettingServer = paramSettingReppository
				.findByParamName(Constants.SERVERMIX_SERVER);
		
		if(paramSettingServer == null){
			//抛出异常
			throw new ServiceHandlerException("更新失败，" + CommonUtils.MSG_NONE_SERVICE_MIX_SETTING,
					CommonUtils.CODE_NONE_SERVICE_MIX_SETTING);
		}
		
		JsonArray jsonDatas = GsonUtil.getDefaultJsonParser()
				.parse(paramSettingServer.getParamValue()).getAsJsonArray();

		boolean flag = false;
		// 通过循环objectIds判断主程序包是否需要更新
		for (int m = 0; m < objectIds.size(); m++) {
			flag = true;
			DefinedBundle updateDefinedBundle = definedBundleRepository
					.findOne(DefinedBundle.idSpecification(objectIds.get(m)
							.getAsString()));

			for (JsonElement jsonElement : jsonDatas) {
				String ip = jsonElement.getAsJsonObject().get("ip").getAsString();
				String port = jsonElement.getAsJsonObject().get("port").getAsString();
				String socketDelPort = jsonElement.getAsJsonObject().get("SocketDelPort").getAsString();
				// 得到要更新的jar包路径
				String fileName = updateDefinedBundle.getBundleJarName();
				String filePath = getRelativeFileNamePath(updateDefinedBundle.getBundleJarName(), Constants.INSTALL_BUNDLE_SERVER_PATH);
				// 调用新的更新API更新接口部署包
				String updateBundle = "";
				try{
					String bundleRequestAddress = "http://" + ip + ":" + port + Constants.BUNDLE_REQUEST_ADDRESS;
					updateBundle = BundleHandleUtil.updateBundle(
							updateDefinedBundle.getBundleCode(),
							filePath,
							bundleRequestAddress);
				} catch (Exception e) {
					throw new ServiceHandlerException("更新失败，更新接口部署包到 【ip=" + ip + "】 这台Servicemix服务器上失败",0);
				}
				
				if (flag) {
					// 取一台servicemix服务器中的的接口部署包信息进行保存
					JsonObject updateBundleJson = GsonUtil.getDefaultJsonParser().parse(updateBundle).getAsJsonObject();
					List<ESBServer> esbServers = eSBServerFactory.getESBServer();
					for (ESBServer esbServer : esbServers) {
						if (StringUtils.equals(ip,esbServer.getServerAddres())) {
							Bundle findInstallBundle = null;
							try{
							// 根据bundleId调用旧封装的api得到bundle详细信息（旧的api获取不到Bundle名称，主要是用来获取Bundle名称）
								findInstallBundle = esbServer.getRestFactory().getMonitorService()
									.getBundleById(updateBundleJson.get("id").getAsInt()).getData().get(0);

							} catch (Exception e) {
								throw new ServiceHandlerException("更新失败，从 【ip=" + ip + "】 这台Servicemix服务器上获取已更新的接口部署包信息失败",0);
							}
							for (Property property : findInstallBundle
									.getProps()) {
								if (StringUtils.equals(property.getKey(),
										"Bundle Location")) {
									updateDefinedBundle
											.setBundleLocation(property
													.getValue().toString());
								}
							}
							updateDefinedBundle.setBundleCode(String
									.valueOf(findInstallBundle.getId()));
							updateDefinedBundle.setBundleName(findInstallBundle
									.getName());
							updateDefinedBundle.setVersion(findInstallBundle
									.getVersion());
							updateDefinedBundle.setStatus(findInstallBundle
									.getState());
							// 保存更新后的记录
							definedBundleRepository.save(Arrays
									.asList(updateDefinedBundle));

							bundles.add(updateDefinedBundle);
							flag = false;
							break;
						}
					}
				}
				// 删除已更新的bundle
				if(!FileDelCilent.delBundleBySocket(ip, socketDelPort, fileName)){
					throw new ServiceHandlerException("更新失败，从 【ip=" + ip + "】 这台Servicemix服务器上删除已安装的接口部署包失败",0);
				}
			}

		}

	}

	/**
	 * 版本升级
	 * 
	 * @param http
	 *            接口实体
	 * @param bundles
	 *            bundle集合
	 */
	public void httpBundleInfoVersionUpgrade(JsonArray object,
			Set<DefinedBundle> bundles) {
		ParamSetting paramSettingServer = paramSettingReppository
				.findByParamName(Constants.SERVERMIX_SERVER);
		
		if(paramSettingServer == null){
			//抛出异常
			throw new ServiceHandlerException("版本升级失败，" + CommonUtils.MSG_NONE_SERVICE_MIX_SETTING,
					CommonUtils.CODE_NONE_SERVICE_MIX_SETTING);
		}
		
		boolean flag = false;
		
		// 测试服务器是否可以连通
		try {
			ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
		} catch (ServerMixException e) {
			throw new ServiceHandlerException("版本升级失败，" + e.getMessage(), CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
		}
		
		for (int i = 0; i < object.size(); i++) {
			flag = true;
			JsonArray jsonDatas = GsonUtil.getDefaultJsonParser().parse(paramSettingServer.getParamValue()).getAsJsonArray();
			for (JsonElement jsonElement : jsonDatas) {
				
				String ip = jsonElement.getAsJsonObject().get("ip").getAsString();
				String port = jsonElement.getAsJsonObject().get("port").getAsString();
				String socketDelPort = jsonElement.getAsJsonObject().get("SocketDelPort").getAsString();
				
				String location = object.get(i).getAsString();
				String bundlePath = getRelativeFileNamePath(location,Constants.INSTALL_BUNDLE_SERVER_PATH);
				String isStart = "1";

				// 调用新封装的api安装bundle
				String installedBundle = "";
				try{
					String bundleRequestAddress = "http://" + ip + ":" + port + Constants.BUNDLE_REQUEST_ADDRESS;
					
					installedBundle = BundleHandleUtil.installBundle(
							location, bundlePath, isStart, bundleRequestAddress);
					
				} catch (Exception e) {
					throw new ServiceHandlerException("版本升级失败，升级接口部署包到 【ip=" + ip + "】 这台Servicemix服务器上失败",0);
				}
				if (flag) {
					if (StringUtils.isNotBlank(installedBundle)) {
						JsonObject json = GsonUtil.getDefaultJsonParser()
								.parse(installedBundle).getAsJsonObject();
						// 根据bundleId调用旧封装的api得到bundle详细信息（主要是用来获取Bundle名称）
						List<ESBServer> esbServers = eSBServerFactory
								.getESBServer();
						for (ESBServer esbServer : esbServers) {
							if (StringUtils.equals(ip,esbServer.getServerAddres())) {
								Bundle findInstallBundle = null;
								try{
									findInstallBundle = esbServer.getRestFactory().getMonitorService()
											.getBundleById(json.get("id").getAsInt()).getData().get(0);

								} catch (Exception e) {
									throw new ServiceHandlerException("版本升级失败，从 【ip=" + ip + "】 这台Servicemix服务器上获取已升级的接口部署包信息失败",0);
								}
								DefinedBundle definedBundle = new DefinedBundle();

								definedBundle.setBundleLocation(location);
								definedBundle.setIsDefinedBundle("1");
								definedBundle.setBundleCode(String
										.valueOf(findInstallBundle.getId()));
								definedBundle.setBundleName(findInstallBundle
										.getName());
								definedBundle.setVersion(findInstallBundle
										.getVersion());
								definedBundle.setStatus(findInstallBundle
										.getState());
								// 保存更新后的记录
								definedBundleRepository.save(Arrays
										.asList(definedBundle));

								bundles.add(definedBundle);
								flag = false;
								break;
							}
						}
					}
				}
				// 删除已安装的bundle
				if(!FileDelCilent.delBundleBySocket(ip, socketDelPort, location)){
					throw new ServiceHandlerException("版本升级失败，从 【ip=" + ip + "】 这台Servicemix服务器上删除已升级的接口部署包失败",0);
				}
			}
		}

	}

	/**
	 * ftp接口部署包更新
	 * 
	 * @param bundles
	 *            bundle集合
	 * @param object
	 *            更新的接口部署包
	 * @param objectIds
	 *            更新的接口部署包ID
	 */
	public void ftpBundleInfoUpdate(Set<DefinedBundle> bundles,
			JsonArray object, JsonArray objectIds) {
		ParamSetting paramSettingBundlePath = paramSettingReppository
				.findByParamName(Constants.SERVER_HANDLE_BUNDLE_PATH);
		JsonArray jsonDatas = GsonUtil.getDefaultJsonParser()
				.parse(paramSettingBundlePath.getParamValue()).getAsJsonArray();
		boolean flag = false;
		// 通过循环objectIds判断主程序包是否需要更新
		for (int i = 0; i < objectIds.size(); i++) {
			flag = true;
			DefinedBundle updateDefinedBundle = definedBundleRepository
					.findOne(DefinedBundle.idSpecification(objectIds.get(i)
							.getAsString()));

			for (JsonElement jsonElement : jsonDatas) {
				// 获取要更新的接口部署包路径
				String filePath = getRelativeFileNamePath(
						updateDefinedBundle.getBundleJarName(), jsonElement
								.getAsJsonObject().get("bundleServerLocal")
								.getAsString());
				// 调用新封装的bundle API对接口部署包进行更新操作（BundleCode即为bundle的id)
				String updateBundle = BundleHandleUtil.updateBundle(
						updateDefinedBundle.getBundleCode(),
						filePath,
						jsonElement.getAsJsonObject()
								.get("bundleRequestAddress").getAsString());
				if (flag) {
					JsonObject updateBundleJson = GsonUtil
							.getDefaultJsonParser().parse(updateBundle)
							.getAsJsonObject();

					List<ESBServer> esbServers = eSBServerFactory
							.getESBServer();
					for (ESBServer esbServer : esbServers) {
						if (jsonElement.getAsJsonObject().get("uploadServer")
								.getAsString()
								.contains(esbServer.getServerAddres())) {
							// 根据bundleId调用旧封装的api得到bundle详细信息（主要是用来获取Bundle名称）
							Bundle findInstallBundle = esbServer
									.getRestFactory()
									.getMonitorService()
									.getBundleById(
											updateBundleJson.get("id")
													.getAsInt()).getData()
									.get(0);

							for (Property property : findInstallBundle
									.getProps()) {
								if (StringUtils.equals(property.getKey(),
										"Bundle Location")) {
									updateDefinedBundle
											.setBundleLocation(property
													.getValue().toString());
								}
							}
							updateDefinedBundle.setBundleCode(String
									.valueOf(findInstallBundle.getId()));
							updateDefinedBundle.setBundleName(findInstallBundle
									.getName());
							updateDefinedBundle.setVersion(findInstallBundle
									.getVersion());
							updateDefinedBundle.setStatus(findInstallBundle
									.getState());
							// 保存更新后的记录
							definedBundleRepository.save(Arrays
									.asList(updateDefinedBundle));

							bundles.add(updateDefinedBundle);
							flag = false;
							break;
						}
					}
				}
			}
		}
	}

	/**
	 * 审核Ftp接口
	 * 
	 * @param ftp
	 *            ftp实体
	 * @return 类型：boolean
	 */
	public boolean AuditFtpInterface(Ftp ftp, Set<DefinedBundle> definedBundles)
			throws ServiceHandlerException {
		getBundleInfoAndSave(definedBundles, ftp.getType());
		ftpRepository.save(Arrays.asList(ftp));
		return true;
	}

	/**
	 * 审核Http接口
	 * 
	 * @param http
	 *            http实体
	 * @return 类型：boolean
	 */
	public boolean AuditHttpInterface(Http http,
			Set<DefinedBundle> definedBundles) throws ServiceHandlerException {
		getBundleInfoAndSave(definedBundles, http.getType());
		httpRepository.save(Arrays.asList(http));
		return true;
	}

	/**
	 * 审核接口对bundle进行操作
	 * 
	 * @param definedBundles
	 *            自定义bundle集合
	 * @param interfaceType
	 *            接口类型
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 */
	public boolean getBundleInfoAndSave(Set<DefinedBundle> definedBundles,
			String interfaceType) throws ServiceHandlerException {
		ParamSetting paramSettingServer = paramSettingReppository
				.findByParamName(Constants.SERVERMIX_SERVER);
		
		if(paramSettingServer == null){
			//抛出异常
			throw new ServiceHandlerException("审核失败，" + CommonUtils.MSG_NONE_SERVICE_MIX_SETTING,
					CommonUtils.CODE_NONE_SERVICE_MIX_SETTING);
		}
		
		JsonArray jsonDatas = GsonUtil.getDefaultJsonParser()
				.parse(paramSettingServer.getParamValue()).getAsJsonArray();
		
		
		boolean flag = false;
		// 测试服务器是否可以连通
		try {
			ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
		} catch (ServerMixException e) {
			throw new ServiceHandlerException("审核失败，" + e.getMessage(),
					CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
		}

		for (DefinedBundle definedBundle : definedBundles) {
			if (StringUtils.equals(definedBundle.getIsDefinedBundle(), "1")) {
				flag = true;
				for (JsonElement jsonElement : jsonDatas) {
					if (StringUtils.equals(IfType.FTP.ValueCode, interfaceType)) {
						//FTP
					} else {
						// http
						String ip = jsonElement.getAsJsonObject().get("ip").getAsString();
						String port = jsonElement.getAsJsonObject().get("port").getAsString();
						String socketDelPort = jsonElement.getAsJsonObject().get("SocketDelPort").getAsString();
						// 获取上传bundle的jar包名称和bundle路径
						String location = definedBundle.getBundleJarName();
						String bundlePath = getRelativeFileNamePath(definedBundle.getBundleJarName(),Constants.INSTALL_BUNDLE_SERVER_PATH);
						
						String isStart = "1";
						String installedBundle = "";
						try {
							// 调用新封装的api安装bundle
							String bundleRequestAddress = "http://" + ip + ":" + port + Constants.BUNDLE_REQUEST_ADDRESS;
							
							installedBundle = BundleHandleUtil.installBundle(
									location,
									bundlePath,
									isStart,
									bundleRequestAddress);
						} catch (Exception e) {
							throw new ServiceHandlerException("审核失败，安装接口部署包到 【ip=" + ip + "】 这台Servicemix服务器上失败",0);
						}
						if (flag) {
							if (StringUtils.isNotBlank(installedBundle)) {
								JsonObject json = GsonUtil.getDefaultJsonParser().parse(installedBundle).getAsJsonObject();
								// 根据bundleId调用旧封装的api得到bundle详细信息（主要是用来获取Bundle名称）
								List<ESBServer> esbServers = eSBServerFactory
										.getESBServer();
								for (ESBServer esbServer : esbServers) {
									if (StringUtils.equals(ip,esbServer.getServerAddres())) {
										Bundle findInstallBundle = null;
										try{
											findInstallBundle = esbServer.getRestFactory().getMonitorService()
													.getBundleById(json.get("id").getAsInt()).getData().get(0);

										} catch (Exception e) {
											throw new ServiceHandlerException("审核失败，从 【ip=" + ip + "】 这台Servicemix服务器上获取已安装的接口部署包信息失败",0);
										}
										definedBundle.setBundleLocation(location);
										definedBundle.setBundleCode(String.valueOf(findInstallBundle.getId()));
										definedBundle.setBundleName(findInstallBundle
														.getName());
										definedBundle.setVersion(findInstallBundle
														.getVersion());
										definedBundle.setStatus(findInstallBundle
														.getState());
										// 保存更新后的记录
										definedBundleRepository.save(Arrays.asList(definedBundle));
									}
								}
							}
						}
						// 删除已安装的bundle
						if(!FileDelCilent.delBundleBySocket(ip, socketDelPort, location)){
							throw new ServiceHandlerException("审核失败，从 【ip=" + ip + "】 这台Servicemix服务器上删除已安装的接口部署包失败",0);
						}
					}
				}
			}
		}

		return true;
	}

	/**
	 * 更新bundle的状态
	 * 
	 * @param interfaceType
	 *            接口类型
	 * @param findBundles
	 *            接口部署包
	 * @param action
	 *            bundle操作
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 */
	public void updateBundleStatus(String interfaceType,
			Set<DefinedBundle> findBundles, String action)
			throws ServiceHandlerException {
		// 测试servicemix服务器是否可以连通
		try {
			ConnetServerTest.telnetConnect(eSBServerFactory.getESBServer());
		} catch (ServerMixException e) {
			throw new ServiceHandlerException(e.getMessage(),
					CommonUtils.CODE_CONNECT_SERVICEMIX_FAIED);
		}

		List<MonitorService> monitorServers = eSBServerFactory
				.getMonitorService();

		for (DefinedBundle definedBundle : findBundles) {
			if (StringUtils.equals(definedBundle.getIsDefinedBundle(), "1")) {
				try {
					for (MonitorService monitorService : monitorServers) {
						if (StringUtils.equals(interfaceType,
								IfType.FTP.ValueCode)) {
							// ftp
							monitorService.executeBundle(Integer
									.parseInt(definedBundle.getBundleCode()),
									action);
							break;
						} else {
							// http
							monitorService.executeBundle(Integer
									.parseInt(definedBundle.getBundleCode()),
									action);
						}
					}
				} catch (Exception e) {
					if (e.getCause() instanceof ConnectException) {
						if(StringUtils.equals(Constants.STOP, "stop")){
							throw new ServiceHandlerException(
									"停用失败，" + CommonUtils.MSG_CALL_INTERFACES_FAIED,
									CommonUtils.CODE_CALL_INTERFACES_FAIED);
						}else{
							throw new ServiceHandlerException(
									"启用失败，" + CommonUtils.MSG_CALL_INTERFACES_FAIED,
									CommonUtils.CODE_CALL_INTERFACES_FAIED);
						}
						
					} else {
						if(StringUtils.equals(Constants.STOP, "stop")){
							throw new ServiceHandlerException(
									"停用失败，" + CommonUtils.MSG_CALL_INTERFACES_FAIED,
									CommonUtils.CODE_CALL_INTERFACES_FAIED);
						}else{
							throw new ServiceHandlerException(
									"启用失败，" + CommonUtils.MSG_CALL_INTERFACES_FAIED,
									CommonUtils.CODE_CALL_INTERFACES_FAIED);
						}
					}
				}
			}
		}

	}

	/**
	 * 得到文件的路径
	 * 
	 * @param fileName
	 * @return
	 */
	public static File getRelativeFile(String fileName, String filePath) {
		File file = new File(filePath + "/" + fileName);
		return file;
	}

	/**
	 * 根据文件名字对文件进行删除
	 * 
	 * @param fileName
	 * @return
	 */
	public static boolean deleteBundleFile(String fileName, String filePath) {
		File file = getRelativeFile(fileName, filePath);
		if (file.exists()) {
			file.delete();
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 得到文件的路径
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getRelativeFileNamePath(String fileName,
			String installServerPath) {
		return installServerPath + "/" + fileName;
	}

	/**
	 * 根据系统标识获取接口标识
	 * 
	 * @param systemIds
	 *            ：系统标识
	 * @param ifName
	 *            :接口名称
	 * @return
	 */
	public Map<String, Boolean> getSystemExistsHttp(List<String> systemIds,
			String isEnable) {
		String sql = "SELECT s.FIELD_SYSTEM_ID FROM t_cook_bu_field_system s "
				+ "WHERE s.FIELD_SYSTEM_ID IN(:systemIds) "
				+ "AND EXISTS(SELECT h.IF_HTTP_ID FROM t_esb_bu_if_http h WHERE h.FIELD_SYSTEM_ID=s.FIELD_SYSTEM_ID "
				+ "AND h.IS_ENABLE=:isEnable)";

		Query query = entityManager.createNativeQuery(sql);
		query.setParameter("systemIds", systemIds);
		query.setParameter("isEnable", isEnable);
		// 获取结果集
		List<String> objects = query.getResultList();
		if (objects == null || objects.isEmpty()) {
			return new HashMap<>();
		}
		Map<String, Boolean> map = new HashMap<>(objects.size());
		// 转换结果集
		for (String object : objects) {
			map.put(object, true);
		}
		return map;
	}

	/**
	 * 服务浏览中根据系统编码、接口状态获取HTTP接口
	 * 
	 * @param systemCode
	 *            ：系统编码
	 * @param isEnable
	 *            ：接口是否可用
	 * @return
	 */
	public List<Http> getHttpInterfaceInfos(String systemId, List<String> ifIds, String isEnable) {
		String sql = "SELECT h.IF_HTTP_ID,h.IF_CODE,h.IF_NAME, h.IF_TYPE, h.IF_VERSION FROM t_esb_bu_if_http h WHERE h.FIELD_SYSTEM_ID=:systemId"
				+ " AND h.IS_ENABLE=:isEnable AND h.IF_HTTP_ID IN(:ifIds)"
				+ " UNION"
				+ " SELECT f.IF_FTP_ID,f.IF_CODE,f.IF_NAME, f.IF_TYPE, f.IF_VERSION FROM t_esb_bu_if_ftp f WHERE f.FIELD_SYSTEM_ID=:systemId"
				+ " AND f.IS_ENABLE=:isEnable AND f.IF_FTP_ID IN(:ifIds)";

		Query query = entityManager.createNativeQuery(sql);
		query.setParameter("ifIds", ifIds);
		query.setParameter("systemId", systemId);
		query.setParameter("isEnable", isEnable);
		
		// 获取结果集
		List<Object[]> objects = query.getResultList();
		if (objects == null || objects.isEmpty()) {
			return new ArrayList<>(0);
		}
		List<Http> list = new ArrayList<>(objects.size());
		// 转换结果集
		for (Object[] object : objects) {
			Http http = new Http();
			http.setId((String) object[0]);
			http.setCode((String) object[1]);
			http.setName((String) object[2]);
			http.setType((String) object[3]);
			http.setVersion((String) object[4]);
			list.add(http);
		}
		return list;
	}

	/**
	 * 报文管理中根据系统编码、接口状态获取HTTP接口
	 * 
	 * @param systemCode
	 *            ：系统编码
	 * @param isEnable
	 *            ：接口是否可用
	 * @return
	 */
	public List<Http> getHttpInterfaceInfosForMsg(String systemId,
			String isEnable) {
		String sql = "SELECT h.IF_HTTP_ID,h.IF_CODE,h.IF_NAME, h.IF_TYPE, h.IF_VERSION FROM t_esb_bu_if_http h WHERE h.FIELD_SYSTEM_ID=:systemId"
				+ " AND h.IS_ENABLE=:isEnable";

		Query query = entityManager.createNativeQuery(sql);
		query.setParameter("systemId", systemId);
		query.setParameter("isEnable", isEnable);
		// 获取结果集
		List<Object[]> objects = query.getResultList();
		if (objects == null || objects.isEmpty()) {
			return new ArrayList<>(0);
		}
		List<Http> list = new ArrayList<>(objects.size());
		// 转换结果集
		for (Object[] object : objects) {
			Http http = new Http();
			http.setId((String) object[0]);
			http.setCode((String) object[1]);
			http.setName((String) object[2]);
			http.setType((String) object[3]);
			http.setVersion((String) object[4]);
			list.add(http);
		}
		return list;
	}

	/**
	 * 表单校验方法
	 * 
	 * @param json
	 *            表单json数据
	 * @param type
	 *            操作类型
	 * @return
	 * @throws ServiceHandlerException
	 */
	public boolean formCheck(String json, String type)
			throws ServiceHandlerException {
		if (StringUtils.isNotBlank(json)) {
			JsonObject jsonData = GsonUtil.getDefaultJsonParser().parse(json)
					.getAsJsonObject().get("interfaceDatas").getAsJsonObject();
			JsonElement ifCode = jsonData.get("interfaceCode");
			if (ifCode == null) {
				throw new ServiceHandlerException(type
						+ CommonUtils.MSG_INTERFACE_CODE_EMPTY,
						CommonUtils.CODE_INTERFACE_CODE_EMPTY);
			}

			JsonElement ifName = jsonData.get("interfaceName");
			if (ifName == null) {
				throw new ServiceHandlerException(type
						+ CommonUtils.MSG_INTERFACE_NAME_EMPTY,
						CommonUtils.CODE_INTERFACE_NAME_EMPTY);
			}

			JsonElement ifVersion = jsonData.get("interfaceVersion");
			if (ifVersion == null) {
				throw new ServiceHandlerException(type
						+ CommonUtils.MSG_INTERFACE_VERSION_EMPTY,
						CommonUtils.CODE_INTERFACE_VERSION_EMPTY);
			}

			/*
			 * JsonElement ifReqParamMsg = jsonData.get("requestParameterMsg");
			 * if(ifReqParamMsg == null){ throw new ServiceHandlerException(type
			 * + CommonUtils.MSG_INTERFACE_REQUEST_PREMATER_EMPTY,
			 * CommonUtils.CODE_INTERFACE_REQUEST_PREMATER_EMPTY); }
			 */

			/*
			 * JsonElement ifRepParamMsg =
			 * jsonData.get("responseParametersMsg"); if(ifRepParamMsg == null){
			 * checkCode.addProperty("backValue", false);
			 * checkCode.addProperty("errorDes", type + "失败，接口返回参数报文不能为空！");
			 * return checkCode; }
			 */

			JsonElement ifReqOverTime = jsonData.get("overTimeSetting");
			if (ifReqOverTime == null) {
				throw new ServiceHandlerException(type
						+ CommonUtils.MSG_INTERFACE_OVERTIME_EMPTY,
						CommonUtils.CODE_INTERFACE_OVERTIME_EMPTY);
			}

			JsonElement ifReqAlarmThreshold = jsonData.get("alarmThreshold");
			if (ifReqAlarmThreshold == null) {
				throw new ServiceHandlerException(type
						+ CommonUtils.MSG_INTERFACE_ALRAM_THRESHOLD_EMPTY,
						CommonUtils.CODE_INTERFACE_ALRAM_THRESHOLD_EMPTY);
			}

			JsonElement ifReqalarmMax = jsonData.get("alarmMax");
			if (ifReqalarmMax == null) {
				throw new ServiceHandlerException(type
						+ CommonUtils.MSG_INTERFACE_ALRAM_MAX_EMPTY,
						CommonUtils.CODE_INTERFACE_ALRAM_MAX_EMPTY);
			}

		} else {
			throw new ServiceHandlerException(
					type + CommonUtils.MSG_FORM_EMPTY,
					CommonUtils.CODE_FORM_EMPTY);
		}

		return true;
	}

	/**
	 * 获取树形接口
	 * 
	 * @param param
	 * @return
	 * @throws BundleActionException
	 */
	public List<Bundle> getAllBundlesForTree(BaseServiceManagementParam param)
			throws BundleActionException {

		List<Bundle> bundles = baseServiceManagementService
				.findSystemLogLevelInfos(param);
		return bundles;

	}

	/**
	 * 新增或修改Redis中对应数据类
	 * 
	 * @param http
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 */
	public boolean updateHttpRedisData(Http http)
			throws ServiceHandlerException {
		/* HttpJedisProxy httpJedisProxy = new HttpJedisProxy(); */
		try {
			HttpVo target = HttpVo.getInstance(http);
			httpJedisProxy.hset(httpJedisProxy.generateKeyFromObject(target),
					target);
		} catch (JsonProcessingException e) {
			throw new ServiceHandlerException(
					CommonUtils.MSG_JSON_PARSING_ERROR,
					CommonUtils.CODE_JSON_PARSING_ERROR);
		} catch (JedisException e) {
			throw new ServiceHandlerException(
					CommonUtils.MSG_CONNECT_REDIS_FAIED,
					CommonUtils.CODE_CONNECT_REDIS_FAIED);
		} catch (Exception e) {
			throw new ServiceHandlerException(
					CommonUtils.MSG_UPDATE_REDIS_DATA_FAIED,
					CommonUtils.CODE_UPDATE_REDIS_DATA_FAIED);

		}
		return true;
	}

	/**
	 * 删除Redis对应的数据
	 * 
	 * @param http
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 */
	public boolean delHttpRedisData(Http http) throws ServiceHandlerException {
		/* HttpJedisProxy httpJedisProxy = new HttpJedisProxy(); */
		try {
			HttpVo target = HttpVo.getInstance(http);
			httpJedisProxy.hdel(target);
		} catch (JedisException e) {
			throw new ServiceHandlerException(
					CommonUtils.MSG_CONNECT_REDIS_FAIED,
					CommonUtils.CODE_CONNECT_REDIS_FAIED);
		} catch (Exception e) {
			throw new ServiceHandlerException(
					CommonUtils.MSG_UPDATE_REDIS_DATA_FAIED,
					CommonUtils.CODE_UPDATE_REDIS_DATA_FAIED);

		}
		return true;
	}

	/**
	 * 新增或修改Redis中对应接口请求量数据
	 * 
	 * @param ifReqQuantity
	 * @return
	 * @throws ServiceHandlerException
	 *             自定义服务异常类（继承RuntimeException才能实现实物回滚）
	 */
	public boolean updateIfReqQuantityRedisData(IfReqQuantity ifReqQuantity)
			throws ServiceHandlerException {
		/*
		 * IfReqQuantityJedisProxy ifReqQuantityJedisProxy = new
		 * IfReqQuantityJedisProxy();
		 */
		try {
			IfReqQuantityVo target = IfReqQuantityVo.getInstance(ifReqQuantity);
			ifReqQuantityJedisProxy.hset(
					ifReqQuantityJedisProxy.generateKeyFromObject(target),
					target);
		} catch (JsonProcessingException e) {
			throw new ServiceHandlerException(
					CommonUtils.MSG_JSON_PARSING_ERROR,
					CommonUtils.CODE_JSON_PARSING_ERROR);
		} catch (JedisException e) {
			throw new ServiceHandlerException(
					CommonUtils.MSG_CONNECT_REDIS_FAIED,
					CommonUtils.CODE_CONNECT_REDIS_FAIED);
		} catch (Exception e) {
			throw new ServiceHandlerException(
					CommonUtils.MSG_UPDATE_REDIS_DATA_FAIED,
					CommonUtils.CODE_UPDATE_REDIS_DATA_FAIED);

		}
		return true;
	}

}
